This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Fran.Bull
Recipients Fran.Bull, docs@python, m123orning, r.david.murray
Date 2014-01-16.18:46:55
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1389898015.91.0.299532701045.issue20135@psf.upfronthosting.co.za>
In-reply-to
Content
I read the FAQ last night and I couldn't see these answered there either. I would like to try submitting a patch for this one, probably this evening. It will likely be two FAQs in the programming section that go something like:

Why does changing one list change another different list?
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.

Why are my default args wrong?
This happens:

>>> from datetime import datetime
>>> class A(object):
...   def __init__(self, created_time=datetime.now()):
...     self.created_time = created_time
... 
>>> an_a = A()
>>> another_a = A()
>>> an_a.created_time
datetime.datetime(2014, 1, 16, 10, 40, 54, 33283)
>>> another_a.created_time
datetime.datetime(2014, 1, 16, 10, 40, 54, 33283)

because default arguments are evaluated when they're read for the first time by the interpreter. Usually when the class is imported. A good way to get the above to do what you want is to use a default argument of None and check for it, like:
>>> class B(object):
...   def __init__(self, created_time=None):
...     if created_time is None:
...       created_time=datetime.now()
...     self.created_time = created_time
... 
>>> a_b = B()
>>> another_b = B()
>>> a_b.created_time
datetime.datetime(2014, 1, 16, 10, 44, 44, 956710)
>>> another_b.created_time
datetime.datetime(2014, 1, 16, 10, 44, 51, 71311)

Feedback appreciated, particularly I'm not sure if this:
'default arguments are evaluated when they're read for the first time by the interpreter'
is exactly the right language. I guess I'll look it up.
History
Date User Action Args
2014-01-16 18:46:55Fran.Bullsetrecipients: + Fran.Bull, r.david.murray, docs@python, m123orning
2014-01-16 18:46:55Fran.Bullsetmessageid: <1389898015.91.0.299532701045.issue20135@psf.upfronthosting.co.za>
2014-01-16 18:46:55Fran.Bulllinkissue20135 messages
2014-01-16 18:46:55Fran.Bullcreate