Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pycharm: Type hint list of items

Tags:

python

pycharm

My question is different because I made a mistake using type hint.

I found a weird type hinging in pycharm: enter image description here

Example is my own class. But I guess this is less important because the IDE is complaining about list type does not define __getitem__ method which is no true. I'm wondering if it's a bug or I used it in a wrong way.

like image 478
spacegoing Avatar asked Sep 27 '16 23:09

spacegoing


People also ask

Do type hints do anything?

Type hints improve IDEs and linters. They make it much easier to statically reason about your code. Type hints help you build and maintain a cleaner architecture. The act of writing type hints forces you to think about the types in your program.

How do you type hint in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

Are Python type hints good?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.


2 Answers

According to official PEP to denote list of objects you should use typing.List, not list builtin.

from typing import List


class Something:
    pass


def f(seq: List[Something]):  # no warning
    for o in seq:
        print(o)

Update January 2021:

Please note that built-in generics were implemented in Python 3.9, as described in PEP585.

like image 110
Łukasz Rogalski Avatar answered Sep 28 '22 08:09

Łukasz Rogalski


Łukasz explained how to correct your code. I'll explain why the error message says what it does.

list defines __getitem__, true, but that isn't what the error message is complaining about. The error message is saying that type itself, which is the list type's type, doesn't support __getitem__. For list[whatever] to be valid, type would have to define a __getitem__ method, not list.

like image 28
user2357112 supports Monica Avatar answered Sep 28 '22 09:09

user2357112 supports Monica