Kimvais
Kimvais

Reputation: 39548

Porting new.module() to Python3

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.

Upvotes: 2

Views: 1398

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122252

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

Upvotes: 4

Related Questions