Python for Fortran programmers 7: default function arguments
Python arguments can have have a default value, in which case, they become optional. Its similar to Fortran optional arguments, but the implementation and the syntax is pretty different. For immutable objects, everything works as a Fortran programmer would expect. But for mutable objects we tend to be surprised.
Type the following function:
def function(data=): data.append(1) return data
and call the function several times, without arguments (
function()). What is going on?
As usual, you can better visualize this process if you execute the code in: http://www.pythontutor.com
But it’s easy to understand, and if you do, you won’t be confused again. The first thing to remember is that lists are mutable. The second one is that the
def statement is an executable statement, which is executed when the function is defined in that line. As an example, will
Hello from f1! be printed if you execute only these lines of code?
def f1(): print("Hello from f1!") return 1 def f2(x=f1()): pass
See? You are defining functions but you are actually producing output!
So once the function is called and the object data is created, the same object is called all the time, pointing to the same data mutable object.
If you have understood everything, you should be able to predict the output of these lines:
def function(data=): data.append(1) return data print(function()) print(function()) print(function()) f1 = function def function(data=): data.append(1) print("Hello!") return data print(function()) print(function()) print(function()) print("f1 is function:", f1 is function)
You can expand this fascinating subject here: http://effbot.org/zone/default-values.htm from where I stole the example and some ideas, or here: