Newbie: How can I use a string value for a keyword argument?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Feb 25 07:30:50 EST 2008


Doug Morse a écrit :
> Hi,
> 
> My apologies for troubling for what is probably an easy question... it's just
> that can't seem to find an answer to this anywhere (Googling, pydocs, etc.)...
> 
> I have a class method, MyClass.foo(), that takes keyword arguments.  For
> example, I can say:
> 
> x = MyClass()
> x.foo(trials=32)
> 
> Works just fine.
> 
> What I need to be able to do is call foo() with a string value specifying the
> keyword (or both the keyword and value would be fine), something along the
> lines of:
> 
> x = MyClass()
> y = 'trials=32'
> x.foo(y)        # doesn't work

You want something like:

x.foo(**{'trials':32})


> Just for completeness, my goal is simply to read a bunch of key/value pairs
> from an INI file (using ConfigObj) 

ConfigObj being a subclass of dict, you should be able to use it 
directly, ie:

x.foo(**my_config)

If just want to pass a section of the ConfigObj, it should work just the 
same.

HTH



More information about the Python-list mailing list