diff -r cd3fdf21a6e4 Doc/faq/programming.rst --- a/Doc/faq/programming.rst Thu Jan 16 14:15:03 2014 -0800 +++ b/Doc/faq/programming.rst Thu Jan 16 21:25:07 2014 -0800 @@ -208,6 +208,25 @@ declaration for identifying side-effects. +Why does changing one mutable object also change another mutable object? +------------------------------------------------------------------------ + +This happens: + +>>> a = [1, 2, 3] +>>> b = a +>>> b.append(4) +>>> print a +[1, 2, 3, 4] + +because variables are just names for things, in this case ``a`` is the list +we first defined and then ``b = a`` says that ``b`` is also a name for that list. +They are both the same list. To make ``b`` a list that has the same values as +``a`` you can create a new list with ``a``: + +>>> b = list(a) + + Why do lambdas defined in a loop with different values all return the same result? ---------------------------------------------------------------------------------- @@ -1601,6 +1620,69 @@ 13891296 +Why is the value of my default keyword argument not what I expect? +------------------------------------------------------------------ + +Given the following class:: + + from datetime import datetime + class A(object): + def __init__(self, created_time=datetime.now()): + self.created_time = created_time + +this happens: + +>>> first = A() +>>> second = A() +>>> first.created_time +datetime.datetime(2014, 1, 16, 10, 40, 54, 33283) +>>> second.created_time +datetime.datetime(2014, 1, 16, 10, 40, 54, 33283) + +because default arguments are evaluated when the ``def`` statement is first +executed. For example when the class is imported. A good way to get the +desired behavior is to use a default argument of None and check for it, like +this:: + + from datetime import datetime + class B(object): + def __init__(self, created_time=None): + if created_time is None: + created_time = datetime.now() + self.created_time = created_time + +>>> first = B() +>>> second = B() +>>> first.created_time +datetime.datetime(2014, 1, 16, 10, 44, 44, 956710) +>>> second.created_time +datetime.datetime(2014, 1, 16, 10, 44, 51, 71311) + + +Why is changing a mutable object in one instance of a class also changing it in another instance of the same class? +------------------------------------------------------------------------------------------------------------------- + +Given the following class:: + + class A(object): + def __init__(self, numbers=[]): + self.numbers = numbers + +this happens: + +>>> first = A() +>>> second = A() +>>> first.numbers.append(1) +>>> second.numbers +[1] + +because variables are just names for things and because default arguments are +evaluated when the ``def`` statement is executed. For example, first the class +is imported and the ``def`` statement is executed creating an instance of list. +After that, new instances of ``A`` have a variable ``numbers`` that is a name +for that instance of list. + + Modules =======