pythonpython-typingpylintflake8

Python typehints and linters


I've been adding static typechecking to our python project, for example like this:

from typing import List
from something import MyOtherClass

class MyClass:
    def __init__(self) -> None:
        self.some_var = None  # type: List[MyOtherClass]

However, now the linters we use (flake8 and pylint) report for example List as unused variables, since they are not used in actual code. (pep8 handles it fine, by the way).

So we end up changing the code to this:

from typing import List  # noqa # pylint: disable=unused-import
from something import MyOtherClass  # noqa # pylint: disable=unused-import

class MyClass:
    def __init__(self) -> None:
        self.some_var = None  # type: List[MyOtherClass]

Is there any better solution to solve this? We don't want to disable all unused import warnings.


Solution

  • Python 3.6 implements PEP 526: Syntax for Variable Annotations, which as the name suggests introduces new syntax for variable annotations, removing the need for type comments.

    In the new syntax, your code would be rewritten as:

    from typing import List, Optional
    from something import MyOtherClass
    
    class MyClass:
    
        def __init__(self) -> None:
            self.some_var: Optional[List[MyOtherClass]] = None
    

    ... or alternatively:

    from typing import List, Optional
    from something import MyOtherClass
    
    class MyClass:
    
        some_var: Optional[List[MyOtherClass]]
    
        def __init__(self) -> None:
            self.some_var = None
    

    Since List and MyOtherClass now appear as actual tokens in the code, rather than comments, linters should have no trouble acknowledging that they are indeed being used.