Automatic binding of **kwargs to variables

Mike Meyer mwm at mired.org
Sat Oct 29 18:29:52 EDT 2005


"chris.atlee at gmail.com" <chris.atlee at gmail.com> writes:

> 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

You clipped my description of what's wrong with setattr: it doesn't
bind the names in the local namespace, it binds them to an
object. This may be acceptable, but wasn't what the OP asked for.

> 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.

If you're going to do that, why not just specify them explicitly in
the function definition instead of using **kwargs? That takes care of
everything - binding, checking, and providing a default value - in one
swoop.

    <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list