How to type default list initializers in functions

Viewed 1079

I have the following function

def foo(main_list = None):
    if main_list is None:
        main_list = []

    # do stuff with main_list

This is a common Python paradigm because if you have a default list, that list stays the same for all default calls. So you get around that by setting it to be None, and then resetting it the the actual default list inside the function.

When typing this, I'd like to do:

def foo(main_list: List[int] = None):
    if main_list is None:
        main_list = []

    # do stuff with main_list

But Mypy complains because now I'm storing None to a List[int] which isn't right.

Should I...

  1. Make main_list be of type Optional[List[int]]

  2. Add in a # type: ignore (which will also remove all the typing from the other parameters that work just fine)

  3. Some other better way of getting around this

(I really hope that the answer is #3, which is why I'm asking. Right now in my code, I have opted for option #2.)

1 Answers

Just use Optional[List[int]]. You're not losing anything by making the parameter optional - you're explicitly handling None within the body of the function - so there's no reason to not use the correct type. It's Pythonic to treat empty lists and None identically anyways.

The problem with # type: ignore, as you mentioned, is that it suppresses type checking for other parameters.

Related