Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 61b1d3e

Browse files
committed
Python: CG trace: Handle subscript
1 parent 79c2c68 commit 61b1d3e

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Foo:
2+
def __getitem__(self, key):
3+
print("__getitem__")
4+
5+
6+
foo = Foo()
7+
foo["key"] # this is recorded as a call :)

python/tools/recorded-call-graph-metrics/src/cg_trace/bytecode_reconstructor.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,15 @@ def __str__(self):
4545
return f"{self.object}.{self.attr_name}"
4646

4747

48+
@dataclasses.dataclass(frozen=True, eq=True, order=True)
49+
class BytecodeSubscript(BytecodeExpr):
50+
key: BytecodeExpr
51+
object: BytecodeExpr
52+
53+
def __str__(self):
54+
return f"{self.object}[{self.key}]"
55+
56+
4857
@dataclasses.dataclass(frozen=True, eq=True, order=True)
4958
class BytecodeCall(BytecodeExpr):
5059
function: BytecodeExpr
@@ -147,6 +156,11 @@ def expr_from_instruction(instructions: List[Instruction], index: int) -> Byteco
147156
obj_expr = expr_that_added_elem_to_stack(instructions, index - 1, 0)
148157
return BytecodeAttribute(attr_name=attr_name, object=obj_expr)
149158

159+
elif inst.opname in ["BINARY_SUBSCR"]:
160+
key_expr = expr_that_added_elem_to_stack(instructions, index - 1, 0)
161+
obj_expr = expr_that_added_elem_to_stack(instructions, index - 1, 1)
162+
return BytecodeSubscript(key=key_expr, object=obj_expr)
163+
150164
# https://docs.python.org/3/library/dis.html#opcode-CALL_FUNCTION
151165
elif inst.opname in ["CALL_FUNCTION", "CALL_METHOD", "CALL_FUNCTION_KW"]:
152166
assert index > 0

0 commit comments

Comments
 (0)