Search code examples
pythondefaultoptional-parametersoptional-arguments

Optional argument with default value in Python


I have seen the optional arguments with deafult value below:

def call_parser(type: Optional[str] = None):

I am not clear its purpose. If the type is provided why do we need to assign default value? Is there any explanation or example related to optional parameter with default value.


Solution

  • Optional[str] is equivalent to Union[str, None].

    Meaning the variable "type" can take values of type str or None value.

    If you set it to a default value then you don't need to write that variable when calling this function.