Python 模块名称中带有破折号或连字符 (-)

发布于 2024-12-07 03:36:40 字数 221 浏览 1 评论 0原文

我有一个现有的 python 模块,其名称中带有破折号 foo-bar.py

更改模块名称是我希望避免的事情,因为该模块是共享的,并且我必须追踪使用它的所有位置,以便我的特殊情况会起作用。

有没有办法加载名称包含通常禁止的“-”的模块?

(我确实知道这不是最佳实践。但对于这种情况,我宁愿不重新设计和测试更大的应用程序集。而且我认为我的公司大师不会批准我花时间实施这样的改变。)

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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

隱形的亼 2024-12-14 03:36:40

您可以使用 __import__() 来完成此操作。例如:

foobar = __import__("foo-bar")

但是您确实应该重命名该模块。这样,您可以避免模块的文件名与程序中使用的标识符不同的混乱。

You can do that using __import__(). For example:

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.

世界等同你 2024-12-14 03:36:40

我知道这个问题已经得到了令提问者满意的回答,但这是另一个答案,我认为它比使用 __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 +

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文