Re: Automatic binding of **kwargs to variables
- From: Steven D'Aprano <steve@xxxxxxxxxxxxxxxxxxxxxx>
- Date: Sun, 30 Oct 2005 23:31:53 +1100
On Sat, 29 Oct 2005 11:01:02 -0700, chris.atlee@xxxxxxxxx wrote:
> Mike Meyer wrote:
> [snip]
>> for name, value in kwargs.items():
>> if name in ('a', 'list', 'of', 'valid', 'keywords'):
>> exec "%s = %s" % (name, value)
>> else:
>> raise ValueError, "Unrecognized keyword " + name
>>
>> Others will probably tell you that you really shouldn't be using exec.
>
> What about using setattr?
>
> for name, value in kwargs.items():
> if name in ('a', 'list', 'of', 'valid', 'keywords'):
> setattr(self, name, value)
> else:
> raise ValueError, "Unrecognized keyword " + name
>
> I'd probably turn the list of valid keywords into another dictionary to
> make it easy to specify default values for all the parameters as well.
Here's a thought... instead of passing a class instance which you access
with obj.name, why not pass a dict which you access with dict[name]?
I don't understand the purpose of doing all this extra work to stuff
values stored in a dictionary into instance attributes, when it is so easy
to just use the dictionary. What advantage do you get?
--
Steven.
.
- References:
- Automatic binding of **kwargs to variables
- From: lbolognini@xxxxxxxxx
- Automatic binding of **kwargs to variables
- Prev by Date: Re: query a port
- Next by Date: Re: Expanding Python as a macro language
- Previous by thread: Re: Automatic binding of **kwargs to variables
- Next by thread: Re: Automatic binding of **kwargs to variables
- Index(es):