a394f93f9bfd0eba161df7690b12af1812fe106e
2 from opcode
import opname
3 from collections
import defaultdict
6 def get_var_name(frame
):
8 call_index
= frame
.f_lasti
9 call_opc
= opname
[code
.co_code
[call_index
]]
10 if call_opc
!= "CALL_FUNCTION" and call_opc
!= "CALL_FUNCTION_VAR":
14 opc
= opname
[code
.co_code
[index
]]
15 if opc
== "STORE_NAME" or opc
== "STORE_ATTR":
16 name_index
= int(code
.co_code
[index
+1])
17 return code
.co_names
[name_index
]
18 elif opc
== "STORE_FAST":
19 name_index
= int(code
.co_code
[index
+1])
20 return code
.co_varnames
[name_index
]
21 elif opc
== "STORE_DEREF":
22 name_index
= int(code
.co_code
[index
+1])
23 return code
.co_cellvars
[name_index
]
24 elif opc
== "LOAD_GLOBAL" or opc
== "LOAD_ATTR" or opc
== "LOAD_FAST" or opc
== "LOAD_DEREF":
26 elif opc
== "DUP_TOP":
28 elif opc
== "BUILD_LIST":
34 def remove_underscore(s
):
35 if len(s
) > 2 and s
[0] == "_" and s
[1] != "_":
40 def get_obj_var_name(override
=None, default
=None):
44 frame
= inspect
.currentframe().f_back
45 # We can be called via derived classes. Go back the stack frames
46 # until we reach the first class that does not inherit from us.
47 ourclass
= frame
.f_locals
["self"].__class
__
48 while "self" in frame
.f_locals
and isinstance(frame
.f_locals
["self"], ourclass
):
51 vn
= get_var_name(frame
)
55 vn
= remove_underscore(vn
)
58 name_to_idx
= defaultdict(int)
59 classname_to_objs
= dict()
63 for n
, e
in enumerate(l
):
69 def trace_back(varname
=None):
71 frame
= inspect
.currentframe().f_back
.f_back
72 while frame
is not None:
74 varname
= get_var_name(frame
)
75 if varname
is not None:
76 varname
= remove_underscore(varname
)
77 l
.insert(0, (varname
, name_to_idx
[varname
]))
78 name_to_idx
[varname
] += 1
81 obj
= frame
.f_locals
["self"]
84 if hasattr(obj
, "__del__"):
88 if varname
is not None:
89 coname
= frame
.f_code
.co_name
90 if coname
== "<module>":
91 modules
= frame
.f_globals
["__name__"]
92 modules
= modules
.split(".")
93 coname
= modules
[len(modules
)-1]
94 coname
= remove_underscore(coname
)
95 l
.insert(0, (coname
, name_to_idx
[coname
]))
96 name_to_idx
[coname
] += 1
98 classname
= obj
.__class
__.__name
__.lower()
100 objs
= classname_to_objs
[classname
]
102 classname_to_objs
[classname
] = [obj
]
106 idx
= index_id(objs
, obj
)
110 classname
= remove_underscore(classname
)
111 l
.insert(0, (classname
, idx
))