简体   繁体   English

创建 Python Facade 包

[英]Creating Python Façade Package

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.在包的__init__.py我有 python 逻辑来附加 sys.path 以根据运行时配置指向 Bar 包之一。 This leaves me using two python import statements.这让我使用了两个 python 导入语句。

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.我可以将其简化为一个 import 语句并将 Foo 视为正确版本的 Bar 的外观吗? The only was I have found is based on this post .我发现的唯一一个是基于这篇文章 In foo.py's __init__.py :在 foo.py 的__init__.py

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

I would recommend against modifying system.path since that can have implications for unrelated code.我建议不要修改system.path因为这可能会对不相关的代码产生影响。

You can get this behavior by using sys.modules .您可以通过使用sys.modules来获得此行为。 When a module is imported, it is registered in the sys.modules dictionary.导入模块时,它会在sys.modules字典中注册。 You can accomplish this simply by setting the entry for the proxy module when it is imported.您只需在导入时设置代理模块的条目即可完成此操作。

implementation.py:实现.py:

def method():
    print "implemented method"

proxy.py:代理.py:

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

main.py:主要.py:

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

output:输出:

$ python main.py 
implemented method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM