Reputation: 110482
If I have the following function:
def pops(L: list, default=None):
"Pop from the left of the list, or return the default."
return L.pop(0) if L else default
What would be the proper way to add type-hints for this? L
is a list
-- I know that (though of what I have no idea). But default
could be anything -- and by extension, the output could be anything as well. What would be the best way to do this?
Examples:
>>> pops([1,2,3,4])
# 1
>>> pops(['1'])
# '1'
>>> pops([], {})
# {}
>>> pops([], None)
# None
Upvotes: 0
Views: 73
Reputation: 24711
from typing import List, Union, TypeVar
T = TypeVar('T')
K = TypeVar('K')
def pops(L: List[T], default: K = None) -> Union[T, K, None]:
"Pop from the left of the list, or return the default."
return L.pop(0) if L else default
Upvotes: 2