Imagine you have a Python function that takes a list as a parameter.
def my_func(a_list):
...
JavaScriptAnd you would like to use mypy to indicate that a_list
is indeed of type List
, then you would have:
def my_func(a_list: List):
...
JavaScriptThis is pretty straightforward, but if you want to give a_list
a default value, things get a little tricky. You probably already know why you shouldn’t use mutable default values in Python function definitions, so one way that you can provide a default (None
) value while still maintaining the type hint is to do the following:
def my_func(a_list: List | None = None):
if a_list is None:
...
JavaScriptNow, what if you would like to specify exactly which values a_list
can have and define a default value? You can do this by changing the type of a_list
to be an iterable with specific values and a default, like this:
def my_func(a_list: Iterable[Literal['default_value', 'other_value']] =('default_value',)):
if a_list == ('default_value',):
...
JavaScriptThis way you can have the default value of a_list
and have the static analyzer check for exact values of a_list
!
For example, here are some examples of whether a mypy
check passes or fails:
my_func() # passes
my_func(('default_value',)) # passes
my_func(['default_value']) # passes
my_func(('other_value',)) # passes
my_func(['other_value']) # passes
my_func(['not_valid']) # fails
JavaScript
Leave a Reply