Given a type t
(originally comes from function annotations), I need to create a default value of that type. Normally, t()
will do just that and work for many types, including basic types such as bool
or int
. However, tuple[bool, int]()
returns an empty tuple, which is not a correct default value. It can get slightly trickier with more complex types such as tuple[bool, list[int]]
.
I saw that tuple[bool, int].__args__
returns (<class 'bool'>, <class 'int'>)
, which might be useful for writing a recursive function that implements this, but I’m still having trouble with this.
Is there an existing function to do this and return the default value? If not, how would I write this code to work with all standard types?
I’m using Python 3.11.
2
Since tuple
is the only instantiable standard type where the default value should not be just an instantiation of the type with no argument, you can simply special-case it in a function that recursively creates a default value for a given type:
from types import GenericAlias
def get_default_value(typ):
if isinstance(typ, GenericAlias) and issubclass(typ.__origin__, tuple):
return typ(map(get_default_value, typ.__args__))
return typ()
so that:
print(get_default_value(tuple[bool, list[int]]))
outputs:
(False, [])
Demo: https://ideone.com/wlb6TL