Skip to content

Instantly share code, notes, and snippets.

@cppio
Last active October 15, 2025 05:20
Show Gist options
  • Select an option

  • Save cppio/d7c37094cd6bd82bce3022b4497d7440 to your computer and use it in GitHub Desktop.

Select an option

Save cppio/d7c37094cd6bd82bce3022b4497d7440 to your computer and use it in GitHub Desktop.
import dis, sys
def varnames():
frame = sys._getframe(1)
instrs = dis.get_instructions(frame.f_code)
instr = next(instr for instr in instrs if instr.offset > frame.f_lasti)
match instr.opname:
case "STORE_FAST" | "STORE_GLOBAL" | "STORE_NAME":
return instr.argval
case "STORE_FAST_LOAD_FAST":
return instr.argval[0]
case "LOAD_FAST" | "LOAD_GLOBAL" | "LOAD_NAME":
instr = next(instrs)
match instr.opname:
case "STORE_ATTR":
return instr.argval
case _:
raise NotImplementedError(repr(instr))
case "UNPACK_SEQUENCE":
variables = []
num_variables = instr.arg
while len(variables) < num_variables:
instr = next(instrs)
match instr.opname:
case "STORE_FAST" | "STORE_GLOBAL" | "STORE_NAME":
variables.append(instr.argval)
case "STORE_FAST_LOAD_FAST":
variables.append(instr.argval[0])
if len(variables) < num_variables:
instr = next(instrs)
match instr.opname:
case "STORE_ATTR":
variables.append(instr.argval)
case _:
raise NotImplementedError(repr(instr))
case "STORE_FAST_STORE_FAST":
variables.extend(instr.argval)
case "LOAD_FAST" | "LOAD_GLOBAL" | "LOAD_NAME":
instr = next(instrs)
match instr.opname:
case "STORE_ATTR":
variables.append(instr.argval)
case _:
raise NotImplementedError(repr(instr))
case _:
raise NotImplementedError(repr(instr))
return variables
case _:
raise NotImplementedError(repr(instr))
x = varnames()
assert x == "x"
x, y, z = varnames()
assert (x, y, z) == ("x", "y", "z")
w = varnames(); x = x
assert w == "w"
x, y, z = varnames(); w = w
assert (x, y, z) == ("x", "y", "z")
class Test:
def __init__(self):
self.x = varnames()
assert self.x == "x"
self.x, self.y, self.z = varnames()
assert (self.x, self.y, self.z) == ("x", "y", "z")
a, self.b, c, self.d, e = varnames(); a = a
assert (a, self.b, c, self.d, e) == ("a", "b", "c", "d", "e")
obj = Test()
obj.i = varnames()
assert obj.i == "i"
obj.j, obj.k = varnames()
assert (obj.j, obj.k) == ("j", "k")
def test():
x = varnames()
assert x == "x"
x, y, z = varnames()
assert (x, y, z) == ("x", "y", "z")
w = varnames(); x = x
assert w == "w"
x, y, z = varnames(); w = w
assert (x, y, z) == ("x", "y", "z")
obj.p = varnames()
assert obj.p == "p"
obj.q, obj.r = varnames()
assert (obj.q, obj.r) == ("q", "r")
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment