Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value in a function in Python [duplicate]

I am noticing the following:

class c:
  def __init__(self, data=[]):
    self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]

Is this the correct behavior?

like image 206
rs1 Avatar asked Feb 22 '10 18:02

rs1


People also ask

What is the default value of a function in Python?

Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

What is the default value of object in file in Python?

The answer is alternative – (a) 0. The default value of reference_point is 0.

What is default value function?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.

Which one function will take when both user and default arguments are given?

Which value will it take when both user and default values are given? Explanation: The default value will be used when the user value is not given, So in this case, the user value will be taken.


3 Answers

Yes, it's correct behavior.

However, from your question, it appears that it's not what you expected.

If you want it to match your expectations, be aware of the following:

Rule 1. Do not use mutable objects as default values.

def anyFunction( arg=[] ):

Will not create a fresh list object. The default list object for arg will be shared all over the place.

Similarly

def anyFunction( arg={} ):

will not create a fresh dict object. This default dict will be shared.

class MyClass( object ):
    def __init__( self, arg= None ):
        self.myList= [] if arg is None else arg 

That's a common way to provide a default argument value that is a fresh, empty list object.

like image 93
S.Lott Avatar answered Sep 19 '22 11:09

S.Lott


This is a classic pitfall. See http://zephyrfalcon.org/labs/python_pitfalls.html, section 5: "Mutable default arguments"

like image 27
unutbu Avatar answered Sep 19 '22 11:09

unutbu


Always make functions like this then:

def __init__ ( self, data = None ):
    if data is None:
       data = []

    self._data = data

Alternatively you could also use data = data or [], but that prevents the user from passing empty parameters ('', 0, False etc.).

like image 44
poke Avatar answered Sep 19 '22 11:09

poke