acting on items passed to a method via a dictiomary

Jeremy Bowers jerf at jerf.org
Fri Oct 15 14:49:07 EDT 2004


On Fri, 15 Oct 2004 11:56:12 -0500, Donnal Walter 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
...

It mostly depends on the contents of the "do something with value" that
you have peppered throughout. I would pull out the various "do somethings"
into methods, but other then that, if you need the full flexibility of a
dict that can contain anything and you need to do things with arbitrary
combinations, there is little else to do.

After pulling things out into methods, I'd actually shift the "if"
statement into the method and do something like the following:

def setup(self, items = None):
    if items is None:
        items = {}

    self.items = items

    for method in ('something', 'another', 'spam', 'eggs'):
        getattr(self, method)()

which will make it more flexible in the long term.

A few other things leap to mind (might want to separate the self.item
setting from the loop, so children can override the loop without messing
up items in calls to the super class; if you don't know what I mean
because I'm being somewhat vague here, don't worry :-) ), but that's about
all you can do without getting silly.



More information about the Python-list mailing list