3 ms·
You forgot mutable default arguments! def fn(ls=[]): ls += [1] return len(ls) (My syntax might be a little off, but you get the idea.) This w
by tikhonj 15y ago
You forgot mutable default arguments!
def fn(ls=[]):
ls += [1]
return len(ls)
(My syntax might be a little off, but you get the idea.)
This will return an ever-increasing number if called repeatedly with no arguments.
Also, the reliance on tuples, particularly tuples of one item always gets me because (1) and (1,) are different.
Also, the scoping for list comprehensions doesn't make sense:
x = 11
[x for x in [1,2,3]]
print x # 3!
This has also gotten me in the past.
- pnathan 15y agoyes, those are nasty little gotchas.
- llimllib 15y agoJust for the record list comp scoping is fixed in python 3: $ python3 Python 3.2.1 (default, Aug 1 2011, 14:47:14) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = 11 >>> [x for x in [1,2,3]] [1, 2, 3] >>> x 11
- randallsquared 15y agoThe problem is not that the argument is mutable, it's that the default argument creation is run at definition time. Mutable arguments are quite useful, and it's consistent to be able to use default arguments in this way; the argument shouldn't outlive the function execution, is all.