2

I'm not sure how to describe this, but is there a way to create an façade package that handles multiple versions of a internal package?

Consider:

Foo/
    __init__.py
    A/
       Bar/
       __init__.py
       etc.
    B/
       Bar/
       __init__.py
       etc.
    C/
       Bar/    
       __init__.py
       etc.

Inside Package's __init__.py I have python logic to append the sys.path to point to one of the Bar packages depending on the runtime configuration. This leaves me using two python import statements.

import Foo
import Bar

Can I reduce that to one import statement and treat Foo as a façade for the correct version of Bar. The only was I have found is based on this post. In foo.py's __init__.py:

for attr in dir(bar):
    globals()[attr] = getattr(bar, attr) 

1 Answer 1

0

I would recommend against modifying system.path since that can have implications for unrelated code.

You can get this behavior by using sys.modules. When a module is imported, it is registered in the sys.modules dictionary. You can accomplish this simply by setting the entry for the proxy module when it is imported.

implementation.py:

def method():
    print "implemented method"

proxy.py:

if __name__ != '__main__':
    import sys
    import implementation
    sys.modules[__name__] = implementation

main.py:

if __name__ == '__main__':
    import proxy
    proxy.method()

output:

$ python main.py 
implemented method
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.