阴影内置名称“函数"和“模块"使用 PyCharm [英] Shadows built-in names "function" and "module" with PyCharm
问题描述
我有以下 Python 代码:
I have the following Python code:
function = "Developer"
module = "something"
print(function + " on " + module)
在 PyCharm 2017 中,我有一个气泡,上面写着PyCharm 的阴影内置名称函数"/模块".
With PyCharm 2017, I have a bubble which says "Shadows built-in names "function"/"module" with PyCharm".
我很惊讶,因为函数"和模块"不是内置名称.它们也不是关键字:
I’m surprised because "function" and "module" are not built-in names. They are not keywords either:
import __builtin__
import keyword
assert "function" not in dir(__builtin__) # -> OK
assert "module" not in dir(__builtin__) # -> OK
assert "function" not in keyword.kwlist # -> OK
assert "module" not in keyword.kwlist # -> OK
怎么了?
我使用的是 CPython 2.7,但在使用 3.5 和 3.5 时遇到同样的问题3.6.
I’m using CPython 2.7, but have the same trouble with 3.5 & 3.6.
__builtin__
现在是 Python 3 中的 builtin
.
__builtin__
is now builtins
in Python 3.
推荐答案
function
is "defined" in builtins.pyi
:
function
is "defined" in builtins.pyi
:
class function:
# TODO not defined in builtins!
__name__ = ... # type: str
__qualname__ = ... # type: str
__module__ = ... # type: str
__code__ = ... # type: Any
__annotations__ = ... # type: Dict[str, Any]
请记住,我使用了已定义"与已定义.看看这个荒谬之处:
Keep in mind I used "defined" vs defined. Check out this absurdity:
foo = function
加注
Traceback (most recent call last):
File "main.py", line 117, in <module>
foo = function
NameError: name 'function' is not defined
然而,如果你执行 function = 'a'
,IDE 会抱怨(如你所见)这掩盖了一个内置名称(即使 function
显然不是实际上已定义).
Yet if you do function = 'a'
the IDE will complain (as you noticed) that this shadows a built-in name (even though function
is clearly not actually defined).
使用 module
重复确切的行为.
The exact behavior repeats with module
.
这是因为(据我所知,如果我错了,请任何人纠正我)pyi
文件仅用于提供类型提示(如 PEP-484 建议).
This is because (as far as I understand, anyone please correct me if I'm wrong) pyi
files are only there to provide type hints (as PEP-484 suggests).
所以,我不确定这个警告是 Pycharm 的 linter 中的错误(也许它不应该查看 .pyi
文件中的定义")还是预期的行为.
So, I'm not sure if this warning is a bug in Pycharm's linter (perhaps it should not be looking at "definitions" in .pyi
files) or an intended behavior.
无论如何,module 和 function 可能都不是好的变量名.
Either way, module and function are probably not good variable names anyway.
这篇关于阴影内置名称“函数"和“模块"使用 PyCharm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!