kecebongsoft
kecebongsoft

Reputation: 271

Python: Getting variable name assigned to a method

I am trying to figure out how to get a variable name I have assigned to a method, for example:

import inspect

def a():
    print inspect.stack()[0][3]

b = a
b()

This will return a instead of b, and if I use [1][3] for the indices, it will give me <module>. I am expecting to get b. Is there any simple pythonic solution for this? Do i have to create decorators and wrappers only to get this?.

Upvotes: 0

Views: 98

Answers (1)

glglgl
glglgl

Reputation: 91049

There is no (easy) way to do so.

That is getting put into the stack frame is not the name the function is called with, but the name which is written in the code object of the function a.func_code.co_name.

There is no way to detect how a function is called. You could try to inspect the code one level above:

With the function changed to

def a():
    return inspect.stack()

we can see

>>> import dis
>>> f=a()[1][0]
>>> dis.dis(f.f_code)
  1           0 LOAD_NAME                0 (a)
              3 CALL_FUNCTION            0
              6 LOAD_CONST               0 (1)
              9 BINARY_SUBSCR
             10 LOAD_CONST               1 (0)
             13 BINARY_SUBSCR
             14 STORE_NAME               1 (f)
             17 LOAD_CONST               2 (None)
             20 RETURN_VALUE
>>> b=a
>>> f=b()[1][0]
>>> dis.dis(f.f_code)
  1           0 LOAD_NAME                0 (b)
              3 CALL_FUNCTION            0
              6 LOAD_CONST               0 (1)
              9 BINARY_SUBSCR
             10 LOAD_CONST               1 (0)
             13 BINARY_SUBSCR
             14 STORE_NAME               1 (f)
             17 LOAD_CONST               2 (None)
             20 RETURN_VALUE
>>> f=[b][0]()[1][0]
>>> dis.dis(f.f_code)
  1           0 LOAD_NAME                0 (b)
              3 BUILD_LIST               1
              6 LOAD_CONST               0 (0)
              9 BINARY_SUBSCR
             10 CALL_FUNCTION            0
             13 LOAD_CONST               1 (1)
             16 BINARY_SUBSCR
             17 LOAD_CONST               0 (0)
             20 BINARY_SUBSCR
             21 STORE_NAME               1 (f)
             24 LOAD_CONST               2 (None)
             27 RETURN_VALUE

It would be hard to parse this reliably.

Upvotes: 1

Related Questions