Python如何别名模块名称(重命名保留向后兼容性) [英] Python how to alias module name (rename with preserving backward compatibility)

查看:380
本文介绍了Python如何别名模块名称(重命名保留向后兼容性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 foo 的python包,我在导入中使用它:

I have a python package named foo, which i use in imports:

import foo.conf
from foo.core import Something

现在我需要将 foo 模块重命名为其他内容,假设 bar ,我想这样做:

Now i need to rename the foo module into something else, let's say bar, so i want to do:

import bar.conf
from bar.core import Something

但我想保持与现有代码的向后兼容性,因此旧的( foo。)导入也应该可以正常工作与栏相同。导入。

but i want to maintain backward compatibility with existing code, so the old (foo.) imports should work as well and do the same as the bar. imports.

如何在python 2.7中完成?

How can this be accomplished in python 2.7?

推荐答案

这个强迫你保留一个 foo 目录,但我认为这是让它工作的最好方法。

This forces you to keep a foo directory, but I think it the best way to get this to work.

目录设置:

bar
├── __init__.py
└── baz.py
foo
└── __init__.py

foo_bar.py

bar / __ init __。py 为空。

bar / baz.py working = True

foo / __ init __。py

import sys

# make sure bar is in sys.modules
import bar
# link this module to bar
sys.modules[__name__] = sys.modules['bar']

# Or simply
sys.modules[__name__] = __import__('bar')

foo_bar.py

import foo.baz

assert(hasattr(foo, 'baz') and hasattr(foo.baz, 'worked'))
assert(foo.baz.worked)

import bar
assert(foo is bar)

这篇关于Python如何别名模块名称(重命名保留向后兼容性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆