pythonpycharmpython-typingpython-3.4

Variable type annotations leading to warnings


I'm new to Python development, and trying to get a fix on things. I am using Pycharm for development. I am currently trying to annotate the types of variables for easier access with autocompletion and suggestions. I've tried iterations of the code with mixed results.

This is the code that has a problem:

path = os.path.dirname(os.path.realpath(__file__))  # type: str
components = path.split(os.sep)  # type: list[str]

The first problem displayed is at the opening brace of the type annotation of the second line. It says:

Class 'type' does not define '__getitem__', so the '[]' operator cannot be used on its instances.

I've googled around, and although the problem seems clear, opening the code for the list class clearly shows a method __getitem__:

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """

....

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

Okay, maybe that's not trivial to understand and there's some other loading mechanism at work. And besides, the "problem" seems to be that I used list[str] and not List[str]. So I altered the code:

path = os.path.dirname(os.path.realpath(__file__))  # type: str
components = path.split(os.sep)  # type: List[str]

Now everything breaks: The second line now complains about this:

Expected type 'List[str]', got 'List[str]' instead`

The previous problem regarding __getitem__ yet persists.

Is there a way to annotate these variables without causing problems for the checker? I am not very happy with the Python documentation in that regard, not explicitly stating the return types of their built-in methods. I have to rely on the information Pycharm provides in the documentation pop-ups (Ctrl+q).


Solution

  • It was a right solution to use List[str] instead of list[str] since builtin types could not be used in type hints, the corresponding PEP has not been accepted yet.

    From what module do you import List? I'm unable to reproduce an issue in 2019.3.