Get 2 isolated instances of a python module

前端 未结 5 994
逝去的感伤
逝去的感伤 2021-02-05 14:13

I am interacting with a python 2.x API written in a non-OO way, it uses module-global scope for some internal state driven stuff. It\'s needed in a context where it\'s no longer

相关标签:
5条回答
  • 2021-02-05 14:45

    Just remove the module from sys.modules:

    >>> import sys
    >>> import mod as m1
    >>> m1.x = 1
    >>> del sys.modules['mod']
    >>> import mod as m2
    >>> m2.x = 2
    >>> m1.x
    1
    
    0 讨论(0)
  • 2021-02-05 14:51

    You can try by fooling sys.modules

    import badmodule as badmod1
    
    import sys
    del sys.modules['badmodule']
    
    import badmodule as badmod2
    

    If this works or not of course depends on what the bad module is doing...

    0 讨论(0)
  • 2021-02-05 14:57

    This can be achieved by importing the module via different paths. That is - if in your sys.path you have two different dotted routes to the module, the module cache will create two different instances of the module with different symbol trees, globals and so on.

    This can be used to have multiple versions of a library also.

    Beware that it will lead to exceptions not being caught (as you are trying to catch the wrong symbol).

    0 讨论(0)
  • 2021-02-05 15:02

    Easiest way is to make two copies of the module and import them separately. For example, take your module thingabobber and make two copies named thingabobber1 and thingabobber2. Then just:

    import thingabobber1, thingabobber2
    

    If this isn't feasible, delete the module from sys.modules after initially importing it so you get a second copy on the second import.

    import sys
    
    import thingabobber as thingabobber1
    del sys.modules["thingabobber"]
    import thingabobber as thingabobber2
    
    0 讨论(0)
  • 2021-02-05 15:09

    I haven't used it personally but it seems that Exocet library may help.

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