2 from opcode
import opname
5 class NameNotFound(Exception):
9 def get_var_name(depth
=2):
10 frame
= inspect
.currentframe()
11 for _
in range(depth
):
15 call_index
= frame
.f_lasti
16 call_opc
= opname
[code
.co_code
[call_index
]]
17 if call_opc
not in ("CALL_FUNCTION", "CALL_FUNCTION_KW", "CALL_FUNCTION_EX", "CALL_METHOD"):
20 index
= call_index
+ 2
22 opc
= opname
[code
.co_code
[index
]]
23 if opc
in ("STORE_NAME", "STORE_ATTR"):
24 name_index
= int(code
.co_code
[index
+ 1])
25 return code
.co_names
[name_index
]
26 elif opc
== "STORE_FAST":
27 name_index
= int(code
.co_code
[index
+ 1])
28 return code
.co_varnames
[name_index
]
29 elif opc
== "STORE_DEREF":
30 name_index
= int(code
.co_code
[index
+ 1])
31 return code
.co_cellvars
[name_index
]
32 elif opc
in ("LOAD_GLOBAL", "LOAD_ATTR", "LOAD_FAST", "LOAD_DEREF",
33 "DUP_TOP", "BUILD_LIST"):