dynamically creating variables

Larry Bates larry.bates at websafe.com
Fri Mar 3 23:54:17 CET 2006


rambham at gmail.com wrote:
> I am writing a parser and I have a routine that can digest
> a series of tokes:
> 
> def digest(*args)
> 
> I use it like this: digest("FOR", "IDENT", "EQ", "INTVAL", "COLON").
> This part works fine. My digest function returns a list of the values
> associated with each token.
> 
>   dummy1, ident, dummy2, start = digest("FOR", "IDENT", "EQ", "INTVAL",
> "COLON")
> 
> But I dont like the way this looks and I want my digest routine to do
> more work. I want to be able to specify the variable bindings in the
> call to digest - and not have them be on the LHS of the assignment.
> 
> Ideally I want to call digest like this:
> 
> digest("FOR", ("IDENT",ident), "EQ", ("INTVAL",start), "COLON")
> 
> and have ident and start be local variable defined in the place that
> calls digest.
> 
> Is it possible to do something like that?
> 
> -Ram
> 
Can't do what you want specifically, but you can stuff everything into
a dictionary and pass it around.

I'm not 100% sure I understand what you want to accomplish, but I
hope this helps.  Have digest return a dictionary of tokens/values.

tokenDict=digest("FOR", "IDENT", "EQ", "INTVAL", "COLON")

then refer to things as tokenDict['ident'], tokenDict['start']

-Larry Bates



More information about the Python-list mailing list