[docs] [issue20135] FAQ need list mutation answers

Fran Bull report at bugs.python.org
Thu Jan 16 22:09:24 CET 2014


Fran Bull added the comment:

Perhaps a 3rd FAQ something like this?:

Why is changing a list in one instance of a class also changing it in another instance of the same class?
This happens:
>>> class A(object):
...   def __init__(self, fruit=[]):
...     self.fruit = fruit
... 
>>> an_A = A()
>>> an_A.fruit.append('apple')
>>> another_A = A()
>>> print another_A.fruit
['apple']
>>> another_A.fruit.append('banana')
>>> print another_A.fruit
['apple', 'banana']
>>> print an_A.fruit
['apple', 'banana']
>>> print an_A.fruit is another_A.fruit
True
>>> print an_A.fruit is A().fruit
True

because of a combination of the above two FAQs, first the default argument is evaluated when the 'def' statement is executed and creates an instance of list. After that new instances of A have a variable 'fruit' that is the name for that instance of list.

I'm not sure whether I should be using as general terms as possible for the Q, i.e. 'mutable object' instead of 'list'. I'll reread http://docs.python.org/devguide/documenting.html and the FAQs before writing the patch.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue20135>
_______________________________________


More information about the docs mailing list