acting on items passed to a method via a dictiomary
exarkun at divmod.com
exarkun at divmod.com
Fri Oct 15 13:22:09 EDT 2004
On Fri, 15 Oct 2004 11:56:12 -0500, Donnal Walter <donnal at donnal.net> wrote:
>The following method is defined in one of my classes:
>
> def setup(self, items={}):
> """perform setup based on a dictionary of items"""
> if 'something' in items:
> value = items['something']
> # now do something with value
> if 'another' in items:
> value = items['another']
> # do something else with value
> if 'spam' in items:
> value = items['spam']
> # do yet another thing with value
> if 'eggs' in items:
> value = items['eggs']
> # and so on
>
> The purpose is to set up the object based on values contained in a
> dictionary passed to the setup() method. The dictionary may be empty, or
> it may contain a variable number of items, and it may contain items not
> looked for by the setup() method. Moreover, this method may be
> overridden in subclasses. The approach described above works ok, so I
> suppose I should leave well enough alone, but I have this nagging
> feeling that Python has a way to do this more simply or more elegantly.
> Any suggestion?
One possibility is to split the work into many methods:
def setup(self, items={}):
for k, v in items.itervalues():
fName = "setup_" + k
fObj = getattr(self, fName, None)
if fObj is not None:
fObj(v)
def setup_eggs(self, value):
# ...
def setup_spam(self, value):
# ...
Jp
More information about the Python-list
mailing list