Can I get a value's name

J

jalanb3

Context for this question arises from some recent code. In particular the "replace_line" method, which takes in a regexp to look for, and a replacement for when it matches.

It is supposed to work for single lines only (we add ^ and $ to the regexp), so arguments which have '\n' in them are not accepted.

So at start of the method we search for such bad chars, and the code ends up something like this:

def replace_line(pattern,replacement):
errors = '\n' in pattern and [ 'pattern' ] or []
errors += '\n' in replacement and [ 'replacement' ] or []
values = [ locals()[e] for e in errors ]
# etc, etc, and eventually:
print 'Argument %s is bad : "%s"' % (errors[0],values[0])

And the question arises from that locals() line:
Given a variable name I can use locals() to get the value
Is there a way to do it the other way round
Given the value, can I get the variable name ?

For example, suppose I had started like this (using the variables, not strings with their names)

def replace_line(pattern,replacement):
values = '\n' in pattern and [ pattern ] or []
values += '\n' in replacement and [ replacement ] or []

Can I later get the name "pattern" via values[0]?

If this was an array in another language:
Of course not, values[0] is a copy of the value
so the connection to the variable is lost
But, AFAIK, in Python values[0] is "just a rename" of pattern
so there might be a way to get "through to" the original variable

Thank you for reading this far.
If you were now to start writing, I'd be very grateful indeed.
 

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
473,777
Messages
2,569,604
Members
45,229
Latest member
GloryAngul

Latest Threads

Top