Python如何别名模块名称(重命名保留向后兼容性)

时间:2022-07-12 02:38:20

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

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

import foo.conf
from foo.core import Something

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

现在我需要将foo模块重命名为其他东西,让我们说吧,所以我想这样做:

import bar.conf
from bar.core import Something

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.

但我想保持与现有代码的向后兼容性,因此旧的(foo。)导入也应该起作用并且与bar一样。进口。

How can this be accomplished in python 2.7?

如何在python 2.7中实现?

2 个解决方案

#1


8  

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

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

Directory setup:

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

foo_bar.py

bar/__init__.py is empty.
bar/baz.py: worked = True

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)

#2


4  

Do you mean something like this?

你的意思是这样的吗?

import foo as bar

you can use shortcuts for module imports like:

您可以使用快捷方式进行模块导入,例如:

from numpy import array as arr

in: arr([1,2,3])
out: array([1, 2, 3])

and you can also use more than one alias at a time

并且您也可以一次使用多个别名

from numpy import array as foo
in: foo([1,2,3])
out: array([1, 2, 3])

if your foo is a class you can do:

如果你的foo是一个类,你可以做:

bar=foo()

and call a subfunction of it by:

并通过以下方式调用它的子功能:

bar.conf()

Does this help you?

这对你有帮助吗?

#1


8  

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

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

Directory setup:

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

foo_bar.py

bar/__init__.py is empty.
bar/baz.py: worked = True

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)

#2


4  

Do you mean something like this?

你的意思是这样的吗?

import foo as bar

you can use shortcuts for module imports like:

您可以使用快捷方式进行模块导入,例如:

from numpy import array as arr

in: arr([1,2,3])
out: array([1, 2, 3])

and you can also use more than one alias at a time

并且您也可以一次使用多个别名

from numpy import array as foo
in: foo([1,2,3])
out: array([1, 2, 3])

if your foo is a class you can do:

如果你的foo是一个类,你可以做:

bar=foo()

and call a subfunction of it by:

并通过以下方式调用它的子功能:

bar.conf()

Does this help you?

这对你有帮助吗?