Newbie question...

Quinn Dunkan quinn at seniti.ugcs.caltech.edu
Thu Sep 28 15:09:06 EDT 2000


On 28 Sep 2000 07:28:18 GMT, Mike 'Cat' Perkonigg <blablu at gmx.net> wrote:
>ivnowa at hvision.nl (Hans Nowak) wrote in <39D1FC71.6768 at hvision.nl>:
>
>>y must have an initial value... try inserting  y = 0  before the for.
>>Aside from that, you probably want to use args.values() rather than
>>args.keys().
>>
>>This won't work for your second line (good="a", etc) though, because it
>>uses strings for values, and y is initialized as an integer.
>>
>>If you want a more generic function, you could try:
>>
>>def adder3(**args):
>>    return reduce(lambda x, y, a=args: x+y, args.values())
>>
>>>>> print adder3(good=1, bad=2, ugly=3)
>>6
>>>>> print adder3(good="a", bad="b", ugly="c")
>>"abc"
>
>Why do you add 'a=args' to the lambda parameter list? args is in local 
>namespace and is not a parameter of lambda but a parameter of reduce.

Try taking it out, and see what happens :)

'args' is *not* in the local namespace of the lambda.  You're probably coming
from a lexically scoped language like scheme, but in python there are only two
namespaces: local and global (well, and __builtins__).  lambda won't see
'args' because it's not local or global to the lambda.  python's scoping rules
are a bit unusual, so it's a faq item.

a = 1
# we can see 'a' (local and global) from here
def f():
    b = 2
    # we can see 'b' (local) and 'a' (global) from here
    def g():
        c = 3
        # we can see 'c' (local) and 'a' (global) from here (but not 'b'!)

Passing things in via default args is the usual python trick to emulate
lexical scoping.



More information about the Python-list mailing list