Skip to content

Instantly share code, notes, and snippets.

@JacobCallahan
Created March 12, 2020 19:09
Show Gist options
  • Save JacobCallahan/d29ca6aa8f97380555a4f5bb115ecfbe to your computer and use it in GitHub Desktop.
Save JacobCallahan/d29ca6aa8f97380555a4f5bb115ecfbe to your computer and use it in GitHub Desktop.
python's inspect module has the potential to be incredibly dangerous
import inspect
class Dummy:
def __init__(self, name):
self.name = name
def print_name(self):
print(f"My name is {self.name}")
def call_meth(self, meth):
print(f"I am calling the method: {meth}")
return meth()
class Gadget:
def totally_innocent(self):
caller = inspect.stack()[1][0].f_locals["self"]
setattr(caller, "name", "Dr. Claw")
def add_meth(self):
caller = inspect.stack()[1][0].f_locals["self"]
def nefarious():
for _ in range(5):
print("I'm doing something bad")
setattr(caller, "print_name", nefarious)
def swap(self):
d2 = Dummy("jAcK")
caller = inspect.stack()[1][0].f_locals["self"]
caller.__dict__ = d2.__dict__
my_dummy = Dummy("Todd")
inspector = Gadget()
my_dummy.print_name()
my_dummy.call_meth(inspector.totally_innocent)
my_dummy.print_name()
my_dummy.call_meth(inspector.add_meth)
my_dummy.print_name()
my_dummy.call_meth(inspector.swap)
print(id(my_dummy))
my_dummy.print_name()
print(id(my_dummy))
@JacobCallahan
Copy link
Author

example output

My name is Todd
I am calling the method: <bound method Gadget.totally_innocent of <__main__.Gadget object at 0x7fa794954250>>
My name is Dr. Claw
I am calling the method: <bound method Gadget.add_meth of <__main__.Gadget object at 0x7fa794954250>>
I'm doing something bad
I'm doing something bad
I'm doing something bad
I'm doing something bad
I'm doing something bad
I am calling the method: <bound method Gadget.swap of <__main__.Gadget object at 0x7fa794954250>>
140357729075728
My name is jAcK
140357729075728

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment