dynamically creating variables

R

rambham

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
 
C

Crutcher

Is it possible to do something like that?

No, you can't change the binding of variables in your calling space.
 
L

Larry Bates

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
 
J

James Stroud

Crutcher said:
No, you can't change the binding of variables in your calling space.

Unless your calling space is global

py> def doit():
.... globals()['wilma'] = 'pebbles'
....
py> doit()
py> wilma
'pebbles'

But that would be crazy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,285
Messages
2,571,416
Members
48,109
Latest member
AndresQlb

Latest Threads

Top