**kwds behavior?

Sean Ross sross at connectmail.carleton.ca
Tue Sep 2 17:41:32 CEST 2003


"Paradox" <JoeyTaj at netzero.com> wrote in message
news:924a9f9c.0309020652.212c54eb at posting.google.com...
> Why does the following attempts to pass in keywords arguments not
> work.

Passing in the keyword arguments to the functions testKeywords1, 2 ,3
does work, but you need to access 'x' using kwds['x']. Passing kwds to
locals().update doesn't work because locals is not writable. It might be
better if attempting to write to an non-writable dict raised an exception,
but that is not the current behaviour. So, your call to update has no effect
on the local namespace and, thus, 'x' is not yet defined locally.

> Does anyone know how to accomplish something like this.
[snip]

Well, you can't modify locals directly,  but you can do this -

class record:
    "a simple class to use like a c struct or pascal record"
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

def testKeywords1 (**kwds):
    my = record(**kwds)
    print my.x

    def testNested():
        print my.x
    testNested()

# works
testKeywords1(x=5)

# output
5
5

HTH
Sean






More information about the Python-list mailing list