default value in __init__

Paul McGuire ptmcg at austin.rr.com
Sun Oct 19 03:56:17 EDT 2008


On Oct 14, 1:36 pm, "David C. Ullrich" <dullr... at sprynet.com> wrote:
> > Well... How to say.. Is there any chance these people will read anything
> > *at all* ?
>
> No. That's exactly the point! Basic Python is so transparent that
> you can start using it without reading anything, just looking at
> a few examples. _Because_ of that it's their responsibility to
> ensure that if you look at a few examples you then have a complete
> understanding of the language.
>
I agree, Python really does strive to be intuitive and easy-to-learn.
So the oddity of the behavior of "optional_list_arg=[]" is a recurring
surprise to those who jump first and read documentation later.
Besides the tutorials, reference docs, and FAQs, there are also some
web pages with titles like "Python Gotchas" and "Common Mistakes in
Python" that usually tread this ground too.

> In particular default parameters should work the way the user
> expects! The fact that different users will expect different
> things here is no excuse...
>
Are you being sarcastic?  Short of "import mindreading", I don't know
how Python would know which behavior a given user would expect.  Maybe
instead of a "code smell", this particular Python wart is a "design
smell".

What is surprising is that Python cannot discriminate between this:
y = 100
def f(a,x=y):
  print a+x
>>> f(1)
101
>>> y=200
>>> f(1)
101

and this:

def f(a,x=[]):
  print a+len(x)
  x.append(a)
>>> f(1)
1
>>> f(1)
2
>>> f(1,[1,2,3])
4
>>>

Is x supposed to be a default arg or a "static" arg (in the sense of a
static var within a function as one finds in C)?

-- Paul



More information about the Python-list mailing list