Q from python tut...

Gordon McMillan gmcm at hypernet.com
Tue May 25 09:59:40 EDT 1999


prasad writes:
> 
> I am learning python using the standard tut that came with the
> distri. I know perl a little bit. Here are some of the things that I
> found confusing till section 5.5.
> 
> 
> val = '' or 'aa' or 'bb'
> val gets the value 'aa'
> 
> shouldn't the expr '' or 'aa' or 'bb' evaluate to 0 or 1 and hence
> val getting the value of 0 or 1.

Python has a protocol for determining whether an object considers 
itself "true" or not. Collections (tuples, lists, dicts and 
strings) are true if they're non-empty. The fact that val gets bound 
to the first "true" thing in the RHS is very handy, if somewhat 
surprising at first.

> ------------------------------------------------------------
> 
> def f(a,l = none):
>     if l is none:
>         l = []
>     l.append(a)
>     return l
> 
> The above style has been recommended because by default, l will
> accumulate the values from earlier calls. The above technique is
> supposed to probably initialise it,if no value is passed for l. but
> if nothing is passed for l in calling,the default should
> automatically wipe out the earlier accumulated list. Then why is it
> that the if loop has been specified?
> 
> It's been said that default values are evaluated only once, and at
> the time of function defination. Does that mean that an argument of
> modifiable type will get set to default only the first time and
> later accumulate the earlier values from earlier calls? If this is
> true,it seems like 'static' behaviour of C lang.
> 
> In general The mutable/non-mutable diff,the above static like nature
> of mutables, evaluation of func. arg is rather confusing!!

Yes it is, but you seem to have it. Would it help to know that a 
function is an object, like everything else? This object is 
created when the "def" is first encountered. Among that object's 
attributes are the default args. So a mutable default does indeed 
behave like a "static". It is created exactly once.

- Gordon




More information about the Python-list mailing list