Created
April 22, 2015 23:36
-
-
Save acatton/d6b7a561787ceca6bc73 to your computer and use it in GitHub Desktop.
Here's how you shouldn't monkeypatch your class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The goal of this was to explain gavin why we're doing this:
https://github.com/fusionbox/django-widgy/blob/d1804e5fa48c8b1e7c3d3754b9725e64de3bb574/widgy/debugtoolbar/templates.py#L28