Search code examples
pythonvisual-studio-codepython-3.7pylinttype-hinting

How to skip the Pylint message for function definition in Python?


I have a function definition in my code, which starts with:

def pivotIndex(self, nums: List[int]) -> int:

I installed pylint in Visual Studio Code and now there are tildes symbols beneath the word List:

enter image description here

When running my code, I get an exception:

    def pivotIndex(self, nums: List[int]) -> int:
NameError: name 'List' is not defined

How to skip or rectify the pylint error message?


Solution

  • You need to import the typing.List object:

    from typing import List
    

    Type hinting uses actual Python objects. If you don't, type hinters will complain too:

    $ mypy filename.py
    filename.py:1: error: Name 'List' is not defined
    filename.py:1: note: Did you forget to import it from "typing"? (Suggestion: "from typing import List")
    

    This applies even if you use from __future__ import annotations to postpone evaluation of annotations (see PEP 563), or use a string value with the type hint. You must still import the names as the type hint checker needs to know what exact object they refer to. That's because List can otherwise be just about anything, it is not a built-in name.

    E.g. you could have assigned your own meaning to List somewhere

    List = Union[List, CustomListSubclass]
    

    and then importing that object and using that definition of List would be a valid (if confusing) type hint.

    Note that turning the annotation into a string (nums: 'List[int]) may make pylint error go away, you will still get errors when you use type hinting. The tool checking the hints can't resolve the List object without the import. Until you add from typing import List to the module, you may as well just remove the type hints in that case (e.g. def pivotIndex(self, nums):).