[Python] How to type default list initializers in functions

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    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.)

    Continue reading...

Compartilhe esta Página