Skip to content

Instantly share code, notes, and snippets.

@acatton
Created April 22, 2015 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acatton/d6b7a561787ceca6bc73 to your computer and use it in GitHub Desktop.
Save acatton/d6b7a561787ceca6bc73 to your computer and use it in GitHub Desktop.
Here's how you shouldn't monkeypatch your class
class GrandParent(object):
@classmethod
def call(cls):
return 1
class Parent(GrandParent):
@classmethod
def call(cls):
return 1 + super(Parent, cls).call()
class Child(Parent):
@classmethod
def call(cls):
return 1 + super(Child, cls).call()
assert Child().call() == 3
class Uncle(GrandParent):
@classmethod
def call(cls):
return 1 + super(Uncle, cls).call()
class Inbred(Child, Uncle):
@classmethod
def call(cls):
return 1 + super(Inbred, cls).call()
assert Inbred().call() == 5
# Bad monkeypatching
old_call = Parent.call
def new_call(_cls, *args, **kwargs):
print "Monkeypatched!"
return old_call(*args, **kwargs)
Parent.call = classmethod(new_call)
assert Child.call() == 3
print "Inbred.call() returned:", Inbred.call()
@acatton
Copy link
Author

acatton commented Apr 22, 2015

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