Python module with a dash, or hyphen (-) in its name

I have an existing python module with a dash in its name, 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.)

81808 次浏览

你可以使用 __import__()做到这一点,例如:

foobar = __import__("foo-bar")

但实际上应该重命名模块。这样就可以避免模块的文件名与程序中使用的标识符不同的混淆。

我知道这个问题已经得到了满意的回答,但这里有另一个答案,我相信有一些优点以上使用 __import__()

import importlib
mod = importlib.import_module("path.to.my-module")
# mod.yourmethod()

根据文件:

"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 +