Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Python style, default parameters of functions [duplicate]

This is covered by the Python Tutorial, but I still don't quite understand the reason why Python has this style. Is it purely convention, or is there some explanation behind why Python has the following style regarding default parameters:

My understanding is that Python prefers something=None as opposed to something=[] for default parameters for functions. But...why not use something=[]? Surely this is the convention in other languages, like C

As an example, take these two examples, which are equivalent

def function(arr, L=[]):
    L.append(arr)
    return L

and

def function(arr, L=None):
    if L is None:
        L = []
    L.append(arr)
    return L

My understanding is that the first is "incorrect style" for Python. Why?

EDIT: Ah, I finally understand. I am incorrect above: the two functions are NOT equivalent. Default arguments are evaluated once when the function is defined, not each time the function is called!

like image 727
JesseTrevve Avatar asked Mar 27 '26 19:03

JesseTrevve


1 Answers

When you set a parameter to the value of a list, it is assigned when the function is defined, not when it is called. That is why you'll get different results for calling the function multiple times with the same input parameter. Beware!!!

def function(arr, L=[]):
    L.append(arr)
    return L

arr = [1, 2, 3]

>>> function(arr)
[[1, 2, 3]]

>>> function(arr)
[[1, 2, 3], [1, 2, 3]]
like image 160
Alexander Avatar answered Mar 29 '26 09:03

Alexander