I have an existing python module with a dash in its name, foo-bar.py
我有一个现有的python模块,名为foo-bar.py
Changing the module name is something I would prefer to avoid as the module is shared, and I would have to chase down all the places it is used so that my special case will work.
更改模块名是我希望避免的,因为模块是共享的,我必须查找使用它的所有位置,以便我的特殊情况能够正常工作。
Is there a way to load a module whose name contains the typically forbidden '-'?
是否有一种方法可以加载一个模块,该模块的名称中包含通常被禁止的'-'?
(I do understand that this isn't a best practice. But for this situation I would prefer not to redesign and test a much larger set of applications. Also I don't think my corporate masters would approve of my taking the time to implement such a change.)
我知道这不是最好的做法。但是对于这种情况,我不希望重新设计和测试更大的应用程序集。我也不认为我的公司主管会赞成我花时间实施这样的改变。
2 个解决方案
#1
67
You can do that using __import__()
. For example:
您可以使用__import__()实现这一点。例如:
foobar = __import__("foo-bar")
But you really should rename the module instead. That way you can avoid confusion where the filename of the module is different from the identifier used in the program.
但是您确实应该重命名模块。这样可以避免在模块的文件名与程序中使用的标识符不同的地方出现混淆。
#2
31
I know this question has already been answered to satisfaction of the asker, but here is another answer which I believes has some merit above using __import__()
.
我知道这个问题已经得到了询问者的满意回答,但是这里有另一个我认为比使用__import__()更有价值的答案。
import importlib
mod = importlib.import_module("path.to.my-module")
# mod.yourmethod()
According to the docs:
根据文档:
"This provides an implementation of import which is portable to any
Python interpreter. This also provides an implementation which is
easier to comprehend than one implemented in a programming language
other than Python."
Python 2.7
+ only
Python 2.7 +只
#1
67
You can do that using __import__()
. For example:
您可以使用__import__()实现这一点。例如:
foobar = __import__("foo-bar")
But you really should rename the module instead. That way you can avoid confusion where the filename of the module is different from the identifier used in the program.
但是您确实应该重命名模块。这样可以避免在模块的文件名与程序中使用的标识符不同的地方出现混淆。
#2
31
I know this question has already been answered to satisfaction of the asker, but here is another answer which I believes has some merit above using __import__()
.
我知道这个问题已经得到了询问者的满意回答,但是这里有另一个我认为比使用__import__()更有价值的答案。
import importlib
mod = importlib.import_module("path.to.my-module")
# mod.yourmethod()
According to the docs:
根据文档:
"This provides an implementation of import which is portable to any
Python interpreter. This also provides an implementation which is
easier to comprehend than one implemented in a programming language
other than Python."
Python 2.7
+ only
Python 2.7 +只