模块名称重新定义内置

发布于 2024-09-17 19:37:04 字数 379 浏览 7 评论 0原文

我正在用 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 技术交流群。

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

发布评论

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

评论(3

生生漫 2024-09-24 19:37:04

这是主观的;没有正确答案。

也就是说,对我来说 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?

暖伴 2024-09-24 19:37:04

PEP 20 说:

显式优于隐式。
面对歧义,拒绝猜测的诱惑。
应该有一种——最好只有一种——明显的方法来做到这一点。

mygame.mapmap 更明确。 mygame.boardmygame.terrainmygame.map 更明确。猜测代码是在谈论 __builtins__.map 还是 mygame.map 是非常可怕的,而且大部分都是错误的。

Quoth PEP 20:

Explicit is better than implicit.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.

mygame.map is more explicit than map. mygame.board or mygame.terrain is less ambiguous than mygame.map. Guessing if code is talking about __builtins__.map or mygame.map is frightful and will mostly be wrong.

过去的过去 2024-09-24 19:37:04

选项 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 to map instead of mygame.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.

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