Function Parameters Default Values
We have covered default values for parameters during our discussion of
function parameters.
We now want to explain some more details about that.
Python IS dynamic
- If you are coming from static programming languages (C, C++, Java, C#, Rust, Golang etc..) then you should remind yourself that in python EVERYTHING happens in runtime.
- For example:
1num=5
2if num > 10:
3 def test_func_A():
4 print('test func A')
5else:
6 def test_func_B():
7 print('test func B')
This code creates a function called test_func_B (and not test_func_A).
- This is not a recommended way to write code, but it is a perfect demonstration of Python syntax.
There is a specific moment of a function creation during run-time.
This is the time when the def command is evaluated.
Default values evaluation
- Python documentation says:
Default parameter values are evaluated from left to right when the function definition is executed. (look for that here) - Here's an example, to make it more concrete:
1n = 7
2
3def test_func(num=5+n):
4 print(num)
5
6n = 9
7test_func()
This code fixes the default value of the num parameter to 7.
This is done just once, so calling the function prints 12 (5+7).
- Since the evaluation of the default value happens just once, setting a default value to a mutable value will also happen once:
1def add_to_list(something, lst=[]):
2 lst.append(something)
3 print(lst)
4
5add_to_list('a')
6add_to_list('b')
7add_to_list('c')
This will print:
1['a']
2['a', 'b']
3['a', 'b', 'c']