名称中带有破折号或连字符 (-) 的 Python 模块 [英] Python module with a dash, or hyphen (-) in its name

查看:45
本文介绍了名称中带有破折号或连字符 (-) 的 Python 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的 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.)

推荐答案

你可以使用 __import__().例如:

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.

这篇关于名称中带有破折号或连字符 (-) 的 Python 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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