[Chicago] class continued, or metaclassing + framehackery, or an exercise in never using this because it's BAD... but fun.

Ian Bicking ianb at colorstudy.com
Fri Mar 28 22:51:18 CET 2008


Ian Bicking wrote:
> Brantley Harris wrote:
>> import sys
>>
>> class ContinueMeta(type):
>>     def __new__(cls, name, bases, dct):
>>         if name == 'continued':
>>             return type.__new__(cls, name, bases, dct)
>>         existing = sys._getframe(1).f_locals[name]
>>         for k, v in dct.items():
>>             setattr(existing, k, v)
>>         return existing
>>
>> class continued(object):
>>     __metaclass__ = ContinueMeta
> 
> I think maybe class decorators do this more reasonably.  Something like:
> 
> def monkeypatch(cls):
>      def do_the_patch(new_cls):
>          cls.update(new_cls.__dict__)
>          return cls
>      return do_the_patch
> 
> @monkeypatch(Widget)
> class Widget:
>      def hello(self):
>          print 'hello'
> 
> Of course you need py3k to do this, but you've all upgraded already, right?

OK, I haven't upgraded, so this is all untested, but to make the 
decorator more awesome:

def monkeypatch(cls):
     def do_the_patch(new_cls):
         fake_class = type('Intermediate%s' % cls.__name__, 
cls.__bases__, cls.__dict__)
         cls.__dict__.clear()
         cls.__bases__ += (fake_class,)
         cls.__dict__.update(new_cls.__dict__)
         return cls
     return do_the_patch

Then, maybe you could do:

class Widget(SomethingMoreParent):
     def onclick(self):
         print 'yo!'

w = Widget()

@monkeypatch(Widget):
class Widget:
     def onclick(self):
         super().onclick()
         print 'hey!'

w.onclick()
# yo!
# hey!



I'm not sure this will work, because I don't know how py3k super() 
works.  And I'm fuzzy on how py2k super() works, as except for the class 
decorator syntax itself (which is just equivalent to 
monkeypatch(Widget)(Widget)) this is all valid in Python 2.  I think 
super(Widget, self).onclick() would actually work right.

   Ian


More information about the Chicago mailing list