Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct type hint for an empty list?

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] = []
like image 747
lemi57ssss Avatar asked Jul 23 '17 10:07

lemi57ssss


People also ask

What are type hints in Python?

Python's type hints provide you with optional static typing to leverage the best of both static and dynamic typing. Besides the str type, you can use other built-in types such as int , float , bool , and bytes for type hintings. To check the syntax for type hints, you need to use a static type checker tool.

Are empty lists Falsy?

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument.

How do you write a class hint in Python?

In a type hint, if we specify a type (class), then we mark the variable as containing an instance of that type. To specify that a variable instead contains a type, we need to use type[Cls] (or the old syntax typing. Type ).

What is union type in Python?

Union type; Union[X, Y] is equivalent to X | Y and means either X or Y. To define a union, use e.g. Union[int, str] or the shorthand int | str . Using that shorthand is recommended.


1 Answers

Looking at PEP 484, specifically the section on type comments (the precursor to variable annotations) this does indeed seem like a bug with PyCharm's checker.

Quoting from the PEP:

In non-stub code, there is a similar special case:

from typing import IO

stream = None  # type: IO[str]

Type checkers should not complain about this (despite the value None not matching the given type), nor should they change the inferred type to Optional[...] (despite the rule that does this for annotated arguments with a default value of None ). The assumption here is that other code will ensure that the variable is given a value of the proper type, and all uses can assume that the variable has the given type.

So, in a similar fashion, type-checkers (as mypy currently does), should not complain about the fact that the initializing value you provide doesn't strictly match the annotation.

like image 181
Dimitris Fasarakis Hilliard Avatar answered Oct 08 '22 07:10

Dimitris Fasarakis Hilliard