Examples of how to pass optional arguments in a python function?
Basic python function
Let's start by creating a simple function in python:
def function_test(a,b):
print(a,b)
return None
myfunc(1,2)
gives
1 2
However if we try to pass a third variable
myfunc(1,2,7)
will generate an error message
too many values to unpack (expected 2)
def myfunc(a,b):
print('function print', a,b)
return a, b, a+b
output = myfunc(1,2)
print(output[0])
print(output[1])
print(output[2])
gives
1 2
1
2
3
Passing optional arguments with *args
def myfunc(a,b, *args):
output = a + b
for ar in args:
print('Optional argument:', ar)
output += ar
return output
myfunc(1,2,7)
gives
Optional argument: 7
10
Another example
def myfunc(a,b, *args):
output = a + b
for ar in args:
print('Optional argument:', ar)
output += ar
return output
myfunc(1,2,7,10,20)
gives
Optional argument: 7
Optional argument: 10
Optional argument: 20
40
Pass a list
def myfunc(a,b, *args):
output = a + b
for ar in args:
print('Optional argument:', ar)
return output
l = [7,10,20]
myfunc(1,2,l)
gives
Optional argument: [7, 10, 20]
Pass a dictionary
def myfunc(a,b, *args):
output = a + b
for ar in args:
print('Optional argument:', ar)
return output
d = {'bob':42, 'emma':47}
myfunc(1,2,d)
gives
Optional argument: {'bob': 42, 'emma': 47}
Passing optional arguments with **kwargs
Another possibility is to use **kwargs to name optional variables directly:
def myfunc(a,b, **kwargs):
print('kwargs: ', kwargs)
return None
myfunc(1,2,lang='fr')
gives
{'lang': 'fr'}
In the function to test if there is an optional argument like 'lang' we can use:
if 'lang' in kwargs:
to get the value of the 'lang' variable:
kwargs['lang']
Example
def myfunc(a,b, **kwargs):
print(kwargs)
if 'lang' in kwargs:
print("found it")
print( kwargs['lang'] )
return a + b
myfunc(1,2,lang='fr', )
gives
{'lang': 'fr'}
found it
fr
Global variable
In python we can also define global variables
global c
c = 123
def myfunc(a,b):
print(c)
return a + b
myfunc(1,2)
gives
123