How to generate a module object from a code object in Python

后端 未结 1 478
温柔的废话
温柔的废话 2020-12-28 08:39

Given that I have the code object for a module, how do I get the corresponding module object?

It looks like moduleNames = {}; exec code in moduleNames d

1条回答
  •  借酒劲吻你
    2020-12-28 09:16

    As a comment already indicates, in today's Python the preferred way to instantiate types that don't have built-in names is to call the type obtained via the types module from the standard library:

    >>> import types
    >>> m = types.ModuleType('m', 'The m module')
    

    note that this does not automatically insert the new module in sys.modules:

    >>> import sys
    >>> sys.modules['m']
    Traceback (most recent call last):
      File "", line 1, in 
    KeyError: 'm'
    

    That's a task you must perform by hand:

    >>> sys.modules['m'] = m
    >>> sys.modules['m']
    
    

    This can be important, since a module's code object normally executes after the module's added to sys.modules -- for example, it's perfectly correct for such code to refer to sys.modules[__name__], and that would fail (KeyError) if you forgot this step. After this step, and setting m.__file__ as you already have in your edit,

    >>> code = compile("a=23", "m.py", "exec")
    >>> exec code in m.__dict__
    >>> m.a
    23
    

    (or the Python 3 equivalent where exec is a function, if Python 3 is what you're using, of course;-) is correct (of course, you'll normally have obtained the code object by subtler means than compiling a string, but that's not material to your question;-).

    In older versions of Python you would have used the new module instead of the types module to make a new module object at the start, but new is deprecated since Python 2.6 and removed in Python 3.

    0 讨论(0)
提交回复
热议问题