What is the correct type hint for an empty list?

Viewed 14332

What is the correct type hint for x = []?

The type checker in my PyCharm editor flagged this as an error:

labelframes: List[ttk.LabelFrame] = []

'Optional' is not an option as in:

labelframes: List[Optional[ttk.LabelFrame]] = []

because the documentation for typing.Optional states that this is equivalent to:

labelframes: List[Union[ttk.LabelFrame, None]] = []

and [None] is not [].

I ought to mention that PyCharm doesn't like this either:

labelframes: List[Union[ttk.LabelFrame, None]] = [None]

Whatever type hint I try. PyCharm flags it as an error with, "Expected to return my type hint here, got no return," so I tried:

labelframes: Optional[List[ttk.LabelFrame, None]] = []

That didn't work.

I am aware that PEP 526 has numerous examples which follow the pattern:

x: List[str] = []
2 Answers

lets first write a sample code for empty list and check it using mypy

from typing_extensions import reveal_type

l = []
reveal_type(l)

Now lets run it in the shell

$ mypy test.py

test.py:4: error: Need type annotation for "l" (hint: "l: List[<type>] = ...")
test.py:6: note: Revealed type is "builtins.list[Any]"
Found 1 error in 1 file (checked 1 source file)

Now pay attention to the second line it says that the type is List[Any].

Lets make changes and re-run

from typing import Any, List
from typing_extensions import reveal_type

l : List[Any] = []

reveal_type(l)

and now run mypy

$ mypy test.py

test.py:6: note: Revealed type is "builtins.list[Any]"
Success: no issues found in 1 source file
Related