pythonpython-typingoptional-parameters

Adding optional arguments to a function


I am working on a project where I'm supposed to add new features to an existing codebase. As part of this, I need to add an optional argument to one of the functions but just adding the optional argument is causing some of my unit tests to fail.

The function looks like the following initially:

def function(
    data1: list,
    data2: list,
    opt1: Optional[list],
)

After adding another optional argument it looks like this:

def function(
    data1: list,
    data2: list,
    opt1: Optional[list],
    new: Optional[dict],
)

The only change I'm making in the codebase is adding this optional argument and it is causing some of my unit tests to fail. I was wondering if someone knows what might be the reason ?


Solution

  • Optional[list] means that the argument can either be a list or None. You are still required to pass it from the caller.

    If you want an argument that can be omitted you should use a default value, for example:

    def function(
        data1: list,
        data2: list,
        opt1: Optional[list] = None,
    )
    

    assuming that None means an omitted argument in your function logic.

    Starting with Python 3.10, you can use the | operator to get rid of Union and Optional keywords:

    opt1: list | None = None