Python: How to load a module twice?

后端 未结 3 396
一生所求
一生所求 2020-12-10 06:39

Is there a way to load a module twice in the same python session?
To fill this question with an example: Here is a module:

Mod.py

x = 0


        
相关标签:
3条回答
  • 2020-12-10 06:53

    Deleting an entry from sys.modules will not necessarily work (e.g. it will fail when importing recurly twice, if you want to work with multiple recurly accounts in the same app etc.)

    Another way to accomplish this is:

    >>> import importlib
    >>> spec = importlib.util.find_spec(module_name)
    >>> instance_one = importlib.util.module_from_spec(spec)
    >>> instance_two = importlib.util.module_from_spec(spec)
    >>> instance_one == instance_two
    False
    
    0 讨论(0)
  • 2020-12-10 06:54

    You could use the __import__ function.

    module1 = __import__("module")
    module2 = __import__("module")
    

    Edit: As it turns out, this does not import two separate versions of the module, instead module1 and module2 will point to the same object, as pointed out by Sven.

    0 讨论(0)
  • 2020-12-10 07:10

    Yes, you can load a module twice:

    import mod
    import sys
    del sys.modules["mod"]
    import mod as mod2
    

    Now, mod and mod2 are two instances of the same module.

    That said, I doubt this is ever useful. Use classes instead -- eventually it will be less work.

    Edit: In Python 2.x, you can also use the following code to "manually" import a module:

    import imp
    
    def my_import(name):
        file, pathname, description = imp.find_module(name)
        code = compile(file.read(), pathname, "exec", dont_inherit=True)
        file.close()
        module = imp.new_module(name)
        exec code in module.__dict__
        return module
    

    This solution might be more flexible than the first one. You no longer have to "fight" the import mechanism since you are (partly) rolling your own one. (Note that this implementation doesn't set the __file__, __path__ and __package__ attributes of the module -- if these are needed, just add code to set them.)

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