Shadows built-in names “function” and “module” with PyCharm

前端 未结 2 1860
渐次进展
渐次进展 2021-01-17 14:20

I have the following Python code:

function = \"Developer\"
module = \"something\"
print(function + \" on \" + module)

With PyCharm 2017, I

2条回答
  •  佛祖请我去吃肉
    2021-01-17 14:43

    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
    

    raises

    Traceback (most recent call last):
      File "main.py", line 117, in 
        foo = function
    NameError: name 'function' is not defined
    

    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).

    The exact behavior repeats with module.

    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).

    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.

    Either way, module and function are probably not good variable names anyway.

提交回复
热议问题