Can I get a value's name

John O'Hagan research at johnohagan.com
Mon May 11 14:21:58 EDT 2009


On Mon, 11 May 2009, jalanb3 wrote:

[...]

>
> 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]?
>
[...]

def replace_line(pattern,replacement):
    values = '\n' in pattern and [ pattern ] or []
    values += '\n' in replacement and [replacement] or []
    loc=locals()
    print [i for i in loc if loc[i] is pattern if pattern in values]

will print ['pattern'] if the value of pattern is in values (if there's a 
newline in pattern). Is that what you're after?

HTH,

John



More information about the Python-list mailing list