Pycharm: Type hint list of items

2020-04-07 10:07发布

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.

2条回答
Juvenile、少年°
2楼-- · 2020-04-07 10:22

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

查看更多
聊天终结者
3楼-- · 2020-04-07 10:30

Accoring 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)
查看更多
登录 后发表回答