0

I want a function that can return the variable/object name as str like this :

def get_variable_name (input_variable):
    ## some codes

>>get_variable_name(a)
'a'

>>get_variable_name(mylist)
'mylist'

it looks like silly but i need the function to construct expression regarding to the variable for later on 'exec()'. Can someone help on how to write the 'get_variable_name' ?

martineau
  • 119,623
  • 25
  • 170
  • 301
bigbug
  • 55,954
  • 42
  • 77
  • 96
  • It's *far* more work than you think to do so. – Ignacio Vazquez-Abrams Aug 30 '12 at 02:17
  • why are you doing this? Im almost certain there is a much better way to do what you want (I mean beyond the very brief explanation you gave) – Joran Beasley Aug 30 '12 at 02:22
  • the fundamental problem is that multiple names can point to the same object. – wim Aug 30 '12 at 02:31
  • Wait, you want to get some name of a function argument so that you can use it in *exec*? Almost certainly you've taken two wrong turns, then. This is probably an example of the [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), where instead of asking for help to achieve your goal, you ask for help in implementing your not-very-practical solution. – DSM Aug 30 '12 at 02:32
  • thank you all for the productive answer. I think I have the clue to solve the problem. – bigbug Aug 30 '12 at 03:06
  • ... But if you have the name `a` in order to call `get_variable_name(a)`, then you know what it would return (if it could exist)... `'a'`! – Ben Aug 30 '12 at 05:23

7 Answers7

7

I've seen a few variants on this kind of question several times on SO now. The answer is don't. Learn to use a dict anytime you need association between names and objects. You will thank yourself for this later.

In answer to the question "How can my code discover the name of an object?", here's a quote from Fredrik Lundh (on comp.lang.python):

The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care — so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)…

….and don’t be surprised if you’ll find that it’s known by many names, or no name at all!


Note: It is technically possible to get a list of the names which are bound to an object, at least in CPython implementation. If you're interested to see that demonstrated, see the usage of the inspect module shown in my answer here:

Can an object inspect the name of the variable it's been assigned to?

This technique should only be used in some crazy debugging session, don't use anything like this in your design.

wim
  • 338,267
  • 99
  • 616
  • 750
  • Note that even that link gives you a list of the name*s* (plural) of an object. There isn't really such a thing as "*the* name" of an object. – BrenBarn Aug 30 '12 at 03:01
5

In general it is not possible. When you pass something to a function, you are passing the object, not the name. The same object can have many names or no names. What is the function supposed to do if you call get_variable_name(37)? You should think about why you want to do this, and try to find another way to accomplish your real task.

Edit: If you want get_variable_name(37) to return 37, then if you do a=37 and then do get_variable_name(a), that will also return 37. Once inside the function, it has no way of knowing what the object's "name" was outside.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Im not sure anything is "impossible" but that said it would be very dificult and hackey and subject to breakage – Joran Beasley Aug 30 '12 at 02:24
  • i don't need the value, i just need the str that tell the variable name been input to the function. – bigbug Aug 30 '12 at 02:24
  • i hoped Python provide the build-in '__objname__' for the object. I fail to find that. I just want this feature to add some dynamic for my application. Namely, I will generate a 'str_statement' regarding the variable, and use 'exec(str_statement)' to do the job. I know it is a bad habit, but it is the intuitive and do job quickly. (I build the application for myself, no security issue) – bigbug Aug 30 '12 at 02:33
  • You can dig the name in the parent frame, but that's quite wrong unless he needs it for debugging purposes... – JBernardo Aug 30 '12 at 02:44
  • don't use `exec` for that and don't go looking for code names. learn to use `dict` in case you need some correspondence between names and objects, it will be MORE intuitive and get the job done quickly! – wim Aug 30 '12 at 02:47
0
def getvariablename(vara):
    for k in globals():
        if globals()[k] == vara:
                  return k
     return str(vara)

may work in some instance ...but very subject to breakage... and I would basically never use it in any kind of production code...

basically I cant think of any good reason to do this ... and about a million not to

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Here's a good start, depending on the Python version and runtime you might have to tweak a little. Put a break point and spend sometime to understand the structure of inspect.currentframe()

import inspect

def vprint(v):
    v_name = inspect.currentframe().f_back.f_code.co_names[3]
    print(f"{v_name} ==> {v}")

if __name__ == '__main__':
    x = 15
    vprint(x)

will produce

x ==> 15
nehem
  • 12,775
  • 6
  • 58
  • 84
-1

if you just want to return the name of a variable selected based on user input... so they can keep track of their input, add a variable name in the code as they make selections in addition to the values generated from their selections. for example:

temp = raw_input('Do you want a hot drink?  Type yes or no. ')
size = raw_input('Do you want a large drink? Type yes or no. ')
if temp and size == 'yes':
    drink = HL
    name = 'Large cafe au lait'
if temp and size != 'yes':
    drink = CS
    name = 'Small ice coffee'
print 'You ordered a ', name, '.'

MJ

-1

If your statement to be used in exec() is something like this

a = ["ddd","dfd","444"]

then do something like this

exec('b = a = ["ddd","dfd","444"]')

now you can use 'b' in your code to get a handle on 'a'.

Mike Lee
  • 2,440
  • 26
  • 12
-2

Perhaps you can use traceback.extract_stack() to get the call stack, then extract the variable name(s) from the entry?

def getVarName(a):
    stack = extract_stack()
    print(stack.pop(-2)[3])

bob = 5
getVarName(bob);

Output:

getVarName(bob)
cleong
  • 7,242
  • 4
  • 31
  • 40