模块名称重新定义内置
我正在用 Python 制作一款游戏,将我的模块之一命名为“map”是有意义的。我首选的导入方式是这样做:
from mygame import map
然而,正如 pylint 告诉我的那样,这是重新定义内置函数。处理这个问题的常见方法是什么?以下是我可以提出的选择:
1)忽略 pylint 警告,因为我无论如何都不使用内置地图。
2)更改为:
import mygame
然后在我的代码中引用为 mygame.map 。
3) 将我的地图模块重命名为其他名称(十六进制地图、游戏地图等)。
我倾向于 (2),但我想看看其他人的想法。
I'm making a game in Python, and it makes sense to have one of my modules named 'map'. My preferred way of importing is to do this:
from mygame import map
As pylint is telling me, however, this is redefining a built-in. What's the common way of dealing with this? Here are the choices I can come up with:
1) Ignore the pylint warning since I don't use the built-in map anyway.
2) Change to:
import mygame
then reference as mygame.map throughout my code.
3) Rename my map module to something else (hexmap, gamemap, etc.)
I'm leaning towards (2) but I want to see what other people think.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是主观的;没有正确答案。
也就是说,对我来说 3 是唯一明智的选择。真的真的不要做1;覆盖内置函数几乎从来都不是一个好主意,在这种情况下它尤其令人困惑。 2 更好,但我认为仍然期望任何名为
map
的函数执行一些类似于内置函数的操作。也许
映射
?This is subjective; there's no right answer.
That said, for me 3 is the only sensible option. Really really don't do 1; overwriting builtins is almost never a good idea and in this case it's especially confusing. 2 is better, but I think there is still an expectation that any function called
map
performs some operation similar to that of the builtin.Maybe
mapping
?PEP 20 说:
mygame.map
比map
更明确。mygame.board
或mygame.terrain
比mygame.map
更明确。猜测代码是在谈论__builtins__.map
还是mygame.map
是非常可怕的,而且大部分都是错误的。Quoth PEP 20:
mygame.map
is more explicit thanmap
.mygame.board
ormygame.terrain
is less ambiguous thanmygame.map
. Guessing if code is talking about__builtins__.map
ormygame.map
is frightful and will mostly be wrong.选项 2 或 3 可以,但我认为重命名
map
以免混淆是最容易理解的。这样,您可以获得引用map
而不是mygame.map
所带来的简洁性,但不会遇到任何范围问题。另外,我认为map是一个有点难以描述的变量名称,所以最好给它一个更具体的名称。Options 2 or 3 would work, however I think it would be most understandable to rename
map
so that it can't be confused. That way, you can get the conciseness that referring tomap
instead ofmygame.map
gives you, but you won't have any problems with scope. Also, I think map is a somewhat undescriptive variable name, so it'd be better to give it a more specific name.