开发者

Module name redefines built-in

开发者 https://www.devze.com 2023-01-14 04:24 出处:网络
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:

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 th开发者_如何学Ce 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.


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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消