0

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

1
  • 8
    Why do you think you need to know (one of) the name(s) the function is assigned to? What if the function is only assigned in a list? What are you trying to achieve? Commented Aug 21, 2014 at 7:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.