Case Statements

Chris Angelico rosuav at gmail.com
Wed Mar 16 19:14:18 EDT 2016


On Thu, Mar 17, 2016 at 5:31 AM, Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
> It can be yes. Look at decorators. They don't provide functionality
> we wouldn't have without them.

Really? Okay, try implementing this without decorators:

def monkeypatch(cls):
    orig = globals()[cls.__name__]
    print("Monkeypatch",id(cls),"into",id(orig))
    for attr in dir(cls):
        if not attr.startswith("_"):
            setattr(orig,attr,getattr(cls,attr))
    return orig

class Foo:
    def method1(self):
        print("I am method 1")

print("Foo is currently",id(Foo))
some_object = Foo()

@monkeypatch
class Foo:
    def method2(self):
        print("I am method 2")

print("Foo is now",id(Foo))

some_object.method1()
some_object.method2()


Granted, this is an evil use of decorators, and possibly is exploiting
an undocumented behaviour of CPython, but still... :)

Porting this code to Python 2 is left as an exercise for the reader,
although it would be interesting to see how IronPython, Jython, and
other Pythons handle this. I've tried it in MicroPython and the
behaviour is exactly the same (save that type objects don't have a
__dict__, so I had to adjust the above code - but it's still
compatible with CPython and uPy). Haven't tried PyPy3 yet.

ChrisA



More information about the Python-list mailing list