[EMAIL PROTECTED] wrote:
> Hi,
> 
> I'm writing a hand-written recursive decent parser for SPICE syntax
> parsing.  In one case I have one function that handles a bunch of
> similar cases (you pass the name and the number of tokens you're
> looking for).  In another case I have a function that handles a
> different set of tokens and so it can't use the same arguments as the
> first one, and in fact takes no arguments.  However, these functions
> are semantically similar and are called from the same place one right
> after the other.
> 
> 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.
> 
> I'm trying to do this 'functionally' (i guess), by avoiding
> if-then-elses and just calling out the  functions by accessing them and
> their arguments from the dictionary.
> 
> 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)
> 
> So  basically this doesn't work.  
> 
> Any thoughts?

You could omit the 'args' entry completely and test for this in the 
dispatch:
        'pwl'  : {'func': self.pwldef},\

for name, params in alldict.items():
        try
                args = (name,) + params['args']
        except KeyError:
                args = ()
        params['func'](*args)

Or include the 'name' parameter in the arg list and use an empty tuple 
for the arg to pwldef:

        'exp'  : {'func': self.arbtrandef, 'args':('exp', 2,4)},\
        'pwl'  : {'func': self.pwldef    , 'args': ()},\

for name, params in alldict.items():
        params['func'](*args)

Kent
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to