Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Monkey Patching

import real_class
class faker(object): pass
fake = faker
real_class.time = fake
fake.sleep =
fake.time =
  • handy in emergencies
  • easily abused for NON-emergencies - gives dynamic languages a bad name
  • subtle hidden "communication" via secret obscure pathways (explicit is better)
class Monkey:

    def __init__(self, count):
        self.bananas = count

    def is_hungry(self):
        hungry = True
        if hungry:
            self.eat()

    def eat(self):
        self.bananas -= 1


m = Monkey(10)
print(m.bananas)       # 10
print(m.is_hungry())   # None
print(m.bananas)       # 9

Monkey.eat = lambda self: True

om = Monkey(10)
print(om.bananas)      # 10
print(om.is_hungry())  # None
print(om.bananas)      # 10