Automatic binding of **kwargs to variables
mwm at mired.org
Sat Oct 29 01:59:56 CEST 2005
"lbolognini at gmail.com" <lbolognini at gmail.com> writes:
> I have a very long list of parameters coming from a web form to my
> method foo(self, **kwargs)
> I would like to avoid manually binding the variables to the values
> coming through the **kwargs dictionary, just to keep the code cleaner,
> I'd like to bind them automatically
> I was adviced against doing it by adding stuff to locals such as:
> locals()["x"] = 5
> since the Python Docs say:
> Warning: The contents of this dictionary should not be modified;
> changes may not affect the values of local variables used by the
> Is there a way to do this? Maybe object.__setattr__() or something that
> involves metaclasses?
.__setattr__() will modify the instance variables, not the local
> As I might go touching something that I shouldn't (like locals()) I'd
> like some advice from you before deciding which way to go.
Reference the keyword arguments through the dictionary. Looking up
values by name is what dictionaries are for. Trying to move the names
from a dictionary into the local (or global) namespace is usually a
bad idea. If you don't know all the names in advance, you risk
collisions between the items in the dictionary and the legitimate
inhabitants of the namespace. If you do know all the names in advance,
you need to make sure the keys in the dictionary are in the list of
values you expect, so you need an explicit list.
That said, the most straightforward way to do this that I can think of
is with exec:
for name, value in kwargs.items():
if name in ('a', 'list', 'of', 'valid', 'keywords'):
exec "%s = %s" % (name, value)
raise ValueError, "Unrecognized keyword " + name
Others will probably tell you that you really shouldn't be using exec.
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