Get 2 isolated instances of a python module

前端 未结 5 1042
逝去的感伤
逝去的感伤 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 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
    

提交回复
热议问题