'In Python, how can I type hint a list with an empty default value?
I would like to make a function that looks like this, but I'm aware that default arguments should never be mutable:
def foo(req_list: list, opt_list: list = []):
...
Without type hinting, I know the way to have an optional parameter default to an empty list is:
def bar(req_list, opt_list=None):
if opt_list == None:
opt_list = []
...
But I'm not sure of the correct way to do this with type hinting.
Solution 1:[1]
what you have is semantically correct. although I would do this, kind of echoing your second code block.
def foo(req_list: list, opt_list: list | None = None):
if opt_list is None:
opt_list = []
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cresht |
