2

How would I implement this in Python3:

def import_code(code, name, add_to_sys_modules=False):
    module = new.module(name)
    sys.modules[name] = module
    do_bookkeeping(module)
    exec(code in module.__dict__)

    return module

Seems like neither __import__ nor importlib actually return the module that can be used for bookkeeping.

0

1 Answer 1

4

The new module has been removed from Python 3. You can use types.ModuleType instead, in both Python 2 and 3.

You have your exec() call wrong; it should be:

exec(code, module.__dict__)

You are trying to execute the False result from the code in module.__dict__ expression instead. Using exec() as a function also works in Python 2, so the following works across the major versions:

import types

def import_code(code, name, add_to_sys_modules=False):
    module = types.ModuleType(name)
    if add_to_sys_modules:
        sys.modules[name] = module
    do_bookkeeping(module)
    exec(code, module.__dict__)
    return module
Sign up to request clarification or add additional context in comments.

1 Comment

That's just error made in typing the question in, the actual question is the new module being gone and no way to do new.module(name). Will revise my question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.