2 from opcode
import opname
5 __all__
= ["NameNotFound", "get_var_name", "get_src_loc"]
8 class NameNotFound(Exception):
12 _raise_exception
= object()
15 def get_var_name(depth
=2, default
=_raise_exception
):
16 frame
= sys
._getframe
(depth
)
18 call_index
= frame
.f_lasti
20 call_opc
= opname
[code
.co_code
[call_index
]]
21 if call_opc
in ("EXTENDED_ARG"):
25 if call_opc
not in ("CALL_FUNCTION", "CALL_FUNCTION_KW", "CALL_FUNCTION_EX", "CALL_METHOD"):
28 index
= call_index
+ 2
30 opc
= opname
[code
.co_code
[index
]]
31 if opc
in ("STORE_NAME", "STORE_ATTR"):
32 name_index
= int(code
.co_code
[index
+ 1])
33 return code
.co_names
[name_index
]
34 elif opc
== "STORE_FAST":
35 name_index
= int(code
.co_code
[index
+ 1])
36 return code
.co_varnames
[name_index
]
37 elif opc
== "STORE_DEREF":
38 name_index
= int(code
.co_code
[index
+ 1])
39 return code
.co_cellvars
[name_index
]
40 elif opc
in ("LOAD_GLOBAL", "LOAD_ATTR", "LOAD_FAST", "LOAD_DEREF",
41 "DUP_TOP", "BUILD_LIST"):
44 if default
is _raise_exception
:
50 def get_src_loc(src_loc_at
=0):
51 # n-th frame: get_src_loc()
52 # n-1th frame: caller of get_src_loc() (usually constructor)
53 # n-2th frame: caller of caller (usually user code)
54 frame
= sys
._getframe
(2 + src_loc_at
)
55 return (frame
.f_code
.co_filename
, frame
.f_lineno
)