如果Python内部的模块名和类名具有相同的名称,那么Python中是否存在任何风险?
我想知道对模块和模块内部的类使用完全相同的名称是否有任何风险。
I would like to know if there any risks to use the exact same name for module and a class from inside the module.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
PEP 8 规定模块应该有短的、全小写的名称,而类名使用 CapWords 约定。因此,如果模块和类具有相同的名称,则说明您没有遵循这些样式约定。
从技术上来说,完全没有风险。
The PEP 8 says that modules should have short, all-lowercase names, while class names use the CapWords convention. So, if you have the same name for a module and a class, you're not following those style conventions.
Technically, there's no risk at all.
除了可能让你自己(或其他开发人员)感到困惑之外,我认为它没有任何问题。事实上,标准 Python 模块中有几个这样的例子,例如 random.random 和 pprint.pprint。
学究气的
random
和pprint
是函数而不是类,但如果有的话,风险是相同的Apart from potentially confusing yourself (or other devs), I don't see anything wrong with it. In fact, there are several examples of this in the standard Python modules e.g.
random.random
andpprint.pprint
.p.s. to be pedantic
random
andpprint
are functions rather than classes, but the risks would be equivalent should there be any这不是问题。标准库中的一个示例:
time.time
是一个与封闭模块同名的函数。我可能无法为您提供 stdlib 中的类示例,因为根据 PEP8,而模块名称往往是小写的。
This isn't a problem. An example from standard lib:
time.time
is a function with the same name as the enclosing module.I probably can't give you a class example from stdlib because they have names like MyClass as per the "Class Names" section of PEP8, while module names tend to be lowercase.
这取决于您导入模块的方式。如果您只导入文件而不是类,那么我想它会是这样的
似乎不太理想。如果你使用
那么你会使用像
this depends on how you import the module. If you just import the file and not the class , then I guess it would be something like
which doesn't seem so desirable. if you use
then you would use like
在我看来,类/函数和封闭模块具有相同的名称是不可取的。它有时会导致混乱、错误和浪费时间调试,因为您可能导入了模块而不是类/函数并尝试调用它或访问成员,但 python 解释器会错误提示它不可调用或者该成员不存在。
例如,您有文件
./long/package/path/obfuscating/the/issue/Foo.py
错误导入:
In my opinion, it is undesirable to have the same name for a class/function and the enclosing module. It can sometimes lead to confusion, bugs, and waste of time debugging, because you may have imported the module instead of the class/function and trying to call it or access a member, but python interpreter would error out saying that it is not callable or the member does not exist.
E.g. you have file
./long/package/path/obfuscating/the/issue/Foo.py
Wrong import: