How to Create Functions with Optional Arguments in Python
To create an optional argument for a function in Python, give it a default value. When a value for the optional argument is supplied on the function call it will override the default value.
To demonstrate this, let's create a function with a required and optional argument and run it.
def foo(required_arg, optional_arg = ''):
print(required_arg)
if optional_arg:
print(optional_arg)
foo('Hello')
Hello
In the above example, no second argument is supplied yet it runs with no issues. Now we can supply the second argument like this:
def foo(required_arg, optional_arg = ''):
print(required_arg)
if optional_arg:
print(optional_arg)
foo('Hello', 1)
Hello
1
Allow an Infinite Number of Optional Arguments
To allow an infinite number of additional argument to be passed to a function, use the *args
parameter. Any additional arguments are put in a tuple.
def foo(required_arg, *args):
print(args)
print(type(args))
foo('Hello', 1)
(1,)
<class 'tuple'>