Home > Software engineering >  In Python, how can I type hint a list with an empty default value?
In Python, how can I type hint a list with an empty default value?

Time:03-11

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.

CodePudding user response:

For me i don't understand what you're trying to do. I would prefer you put it in writing so i can help. Thanks

CodePudding user response:

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 = []
    ...
  • Related