How to Specify Default List Value with Types in Python

Imagine you have a Python function that takes a list as a parameter.

def my_func(a_list):
    ...
JavaScript

And 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):
    ...
JavaScript

This 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:
        ...
JavaScript

Now, 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',):
        ...
JavaScript

This 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

Want to keep up to date? Subscribe to the newsletter!

Leave a Reply

Your email address will not be published. Required fields are marked *