Can I get a value's name
jalanb3
yahoo at al-got-rhythm.net
Mon May 11 12:30:03 EDT 2009
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.
--
Alan
P.S. This is just curiosity - replace_lines() works great as is.
More information about the Python-list
mailing list