171 points · by Nurdok · 13y ago · 83 comments
That functionality really should be changed for the next major python release, and have default evaluate each time the function is called - which is how 99.9% of people using it expect it to work.
There's plenty of code out there that rely on default values being assigned a mutable value and changing it -- even in a major point release -- would be far worse off. Python's been around for 20 years; it's too late to make a change like that.
It IS a "wart" in that you need to be aware of it to know that it's an issue, but once you are, it is an obvious thing to spot.
http://stackoverflow.com/questions/1132941/least-astonishmen...
Make lists immutable you mean? Like tuple()? Edit: Or force re-evaluation on every function call (could be pretty slow)?
The best practice is to just use a tuple (immutable) instead of a list to begin with. You can always do mylist = list(defaulttuple) inside your function first thing if you really want to work with it as a list.
Also, both pylint and pep8, two python static analyzers, will all warn you about any mutable default arguments you provide. Many Python developers have these hooked into their editor or precommit hooks to catch things like this (among others).
Lists are largely for homogeneous collections, whereas tuples are heterogeneous. When you mix them, you abuse what they signal to the reader.
Python doesn't do much for type safety. Either accept the pitfalls of mutability as a tradeoff, or subclass list to make a safer type.
This. In particular, tuples are for collections whose length is fixed and meaningful, and for which you could give names to each field. Lists are for collections whose length doesn't correspond to anything in particular and which you could imagine growing and shrinking.
As an aside, django makes this mistake and confuses people: using tuples where semantically they should be lists, presumably out of a desire for immutability.
What? What makes you think that?
It is probably also true (generally speaking) that people tend to use lists when the cardinality is not fixed and tuples otherwise.
def print_now(now=time.time()):
print now
The expectation here is that it will give the current time as the default, but the expectation is broken by the very unexpected behavior of the language. That's the kind of thing you want to avoid if at all possible. I see no reason why anybody would not want the default to evaluate every time - tiny bit of speed seems like a very premature optimization here.If you're worried about speed, you could make a class/instance variable, and then set the default to that variable. That's what 'default' is actually doing in the current implementation - and it sounds unexpected in the extreme.
Now personally I hardly every use default values, but to me, when I see this - > I see no reason why anybody would not want the default to evaluate every time
It means you should have put it in the method.
No, that's not good advice. Tuples are not just immutable lists. See below.
current behavior is totally fine. it is well defined that somelist.append(x) appends x to somelist inplace.
>>> class A(object):
... def method(self, a): pass
...
>>> A().method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 2 arguments (1 given)
Once you understand more about how method dispatch works it makes sense, but it's really confusing to be told you were doing something you don't think you are. >>> class C:
... def m(self,a):
... pass
...
>>> C().m()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: m() missing 1 required positional argument: 'a'
>>>I actually figured it out by printing out the id of the object being modified in my code, and when seeing it was the same had to really scratch my head. Default args are initialized when the function (or similarly, class) is defined, not when executed.
But overall, this is a problem involving documentation, design and naming, and your own mindset.
Ideally you would never really be put in the position of not knowing, because it would be clearly documented. Of course, we all know how well that tends to work.
Second, well-designed systems with good naming practices will make it fairly obvious most of the time what sort of arguments are expected, and what you can expect to get back. (This is related to the next point.)
Finally, coming from a "static" language, your brain just isn't trained to perform its own type inference and deal with duck typing. This is mostly a matter of practice, you get better at it. But if you aren't already familiar with various kinds of typing, be sure to do some reading. A better understanding of the differences will help make sense of what you're seeing.
def print_now(now=time.time):
print now() def print_now(now=None):
now = now or time.time()
print nowI was wrong, and now I know better. Thank you.
def foo(**kwargs):
numbers = kwargs.pop('numbers', [])
numbers.append(9)
print numbersAlso, I really don't like the decision to make Python 2 disobey the system locale and use ascii as the default encoding. Lots of Python programs out there have broken i18n for no good reason because of that (nobody starts teaching python by telling you to use .decode('utf-8')/.encode('utf-8') when you pipe data, and by the time you realize what's wrong, you often already have code out there.)
def f(x=()): x = list(x) ...
def g(y=(())) y = dict(y) ...
f() is the pattern for lists, g() is for dicts. Note that you can pass in regular lists to f() and regular dicts to g().
>>> arrays = [[]] * 5
>>> print arrays
... [[], [], [], [], []]
>>> arrays[0].append(1)
>>> print arrays
... [[1], [1], [1], [1], [1]]If you use a variable it's easier to understand:
a = []
arrays = [a] * 5
What you have now is [a, a, a, a, a], so if you modify one of the lists, it's no wonder they all get modified: they're references to the same list.On the topic of the bug in OP, would a Python newbie expect the similarly confusing behavior caused by interactions between (im)mutability and function arguments being passed as a "reference"?
Using OP's foo():
>>> a = [1,2,3]
>>> foo(a)
[1, 2, 3, 9]
>>> a
[1, 2, 3, 9]
if 'a' were an immutable object like an int, it wouldn't be modified. >>> def bar(n):
n += 1
print(n)
>>> b = 3
>>> bar(b)
4
>>> b
3 def foo(num=[0]):
num[0] = num[0] + 1
return num[0] class Foo:
def __init__(self):
self.n = 0
def __call__(self):
self.n += 1
return self.n
foo = Foo()