Storing nothing in a dictionary and passing it to a function

Roberto Bonvallet rbonvall at gmail.com
Mon Jun 5 18:45:53 EDT 2006


63q2o4i02 at sneakemail.com:
> I'd like to have a dictionary (actually a nested dictionary) to call
> these functions so I can avoid if-then-elsing everything.  Eath
> dictionary item has three things in it: the function to be called, a
> string to pass to the function (which is also the key to the dict), and
> a tuple to pass to the function.  In the case of the function with no
> arguments, obviously I'd like not to pass anything.
[...]
> something like this:
>                 alldict = \
>                         {'pulse': {'func': self.arbtrandef, 'args':(2,5)},\
>                          'sin'  : {'func': self.arbtrandef, 'args':(2,3)},\
>                          'exp'  : {'func': self.arbtrandef, 'args':(2,4)},\
>                          'pwl'  : {'func': self.pwldef    , 'args': (None,)},\  <------- how
> do I store "no" arguments?
>                          'sffm' : {'func': self.arbtrandef, 'args':(5,0)}}
>
>                 for it in alldict.items():
>                         name = it[0]
>                         args = (name,) + it[1]['args']
>                         it[1]['func'](*args)

I would do it like this:

alldict = {
    'pulse': (self.arbtrandef, (2, 5)),   # function and args packed in a tuple
    'sin'  : (self.arbtrandef, (2, 3)),
    'exp'  : (self.arbtrandef, (2, 4)),
    'pwl'  : (self.pwldef, ()),    # empty tuple represented by ()
    'sffm' : (self.arbtrandef, (5, 0)),
}
for (fname, (func, args)) in alldict.items():  # items unpacked directly
    func(fname, *args)

Best regards.
-- 
Roberto Bonvallet



More information about the Python-list mailing list