Farhang Amaji
Farhang Amaji

Reputation: 973

Getting name of local variable at runtime in Python3

I want to get variable name in function so here:

def foo(bar):
    print(getLocalVaribalename(bar))

I want 'bar' to be printed. so I found the code for global variables

def varName(variable,globalOrLocal=globals()):
    for name in list(globalOrLocal.keys()):
        expression = f'id({name})'
        if id(variable) == eval(expression):
            return name

and I sent varName(bar,locals()) to it like this

def foo(bar):
    print(varName(bar,locals()))

but gives NameError: name 'bar' is not defined error.

I also found Getting name of local variable at runtime in Python which is for python 2 but the syntax is completely different. note that the main goal is to get the name of local variable and not necessarily with this code(varName function which is defined few lines earlier).

Upvotes: 0

Views: 259

Answers (1)

jsbueno
jsbueno

Reputation: 110301

import sys
def getlocalnamesforobj(obj):
    frame = sys._getframe(1)
    return [key for key, value in frame.f_locals.items() if value is obj]

This introspects the local variables from the calling function. One obvious problem is, of course, there might be more than one name pointing to the same object, so the function returns a list of names.

As put in the comments, however, I can't perceive how this can be of any use in any real code.

As a rule of thumb, if you need variable names as data (strings), you probably should be using a dictionary to store your data instead.

Upvotes: 1

Related Questions