Intercepting module calls?

后端 未结 5 1141
粉色の甜心
粉色の甜心 2021-01-15 13:20

I\'m trying to \'intercept\' all calls to a specific module, and reroute them to another object. I\'d like to do this so that I can have a fairly simple plugin architecture.

5条回答
  •  生来不讨喜
    2021-01-15 13:23

    In renderer.py:

    import sys
    
    if __name__ != "__main__":
        sys.modules[__name__] = OpenGLRenderer()
    

    The module name is now mapped to the OpenGLRenderer instance, and import renderer in other modules will get the same instance.

    Actually, you don't even need the separate module. You can just do:

    import sys
    sys.modules["renderer"] = OpenGLRenderer()
    import renderer   # gives current module access to the "module"
    

    ... first thing in your main module. Imports of renderer in other modules, once again, will refer to the same instance.

    Are you sure you really want to do this in the first place? It isn't really how people expect modules to behave.

提交回复
热议问题