我有以下Python代码:
function = "Developer"
module = "something"
print(function + " on " + module)
Run Code Online (Sandbox Code Playgroud)
使用PyCharm 2017,我有一个泡泡,上面写着"Shadows内置名称"功能"/"模块"与PyCharm".
我很惊讶,因为"函数"和"模块"不是内置名称.它们也不是关键字:
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
Run Code Online (Sandbox Code Playgroud)
怎么了?
我使用的是CPython 2.7,但3.5和3.6也有同样的问题.
编辑:
__builtin__现在builtins是Python 3.
function被"定义"在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]
Run Code Online (Sandbox Code Playgroud)
请记住,我使用"已定义"与已定义.看看这个荒谬:
foo = function
Run Code Online (Sandbox Code Playgroud)
加薪
Traceback (most recent call last):
File "main.py", line 117, in <module>
foo = function
NameError: name 'function' is not defined
Run Code Online (Sandbox Code Playgroud)
然而,如果你function = 'a'的IDE会抱怨(如你注意到),这隐藏了内置的名字(即使function显然是不实际的定义).
确切的行为重复module.
这是因为(据我所知,任何人请纠正我,如果我错了)pyi文件只提供类型提示(如PEP-484建议).
所以,我不确定这个警告是否是Pycharm的linter中的错误(也许它不应该在.pyi文件中查看"定义" )或预期的行为.
无论哪种方式,模块和函数无论如何都可能不是好的变量名.