Fran Bull added the comment:

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.

----------
nosy: +Fran.Bull

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue20135>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to