Hi. I've posted this code to python-list, but I thought I might post it here as well. This is a metaclass approach to dealing with the issues PEP318 is meant to address. It's a quick hack that allows you to put the method decoration and annotation information before the method definition. I just wanted to see if this could be done without changing the language syntax. Looks like it's atleast a possibility, though this only works with methods, and there are likly other issues I'm not aware of. Anyway, here's the code: import sys def delayed_decorate(method, *decorators, **attributes): "Decorate method during class instantation" method.__dict__.update(attributes) for decorator in decorators: method = decorator(method) return method def decorate(funcname, *decorators, **attributes): "Mark method for delayed decoration" clsdict = sys._getframe(1).f_locals clsdict.setdefault("decorated", {})[funcname] = \ (decorators, attributes) class MetaDecorate(type): "Enables delayed decoration and annotation of methods" def __new__(klass, name, bases, _dict): if "decorated" in _dict: for m, (d, a) in _dict["decorated"].iteritems(): _dict[m] = delayed_decorate(_dict[m], *d, **a) del _dict["decorated"] return type.__new__(klass, name, bases, _dict) class Decorated(object): __metaclass__ = MetaDecorate class C(Decorated): a = "A" decorate("f", classmethod, author="Sean Ross", version="0.9.2") def f(klass): return klass.a decorate("g", staticmethod) def g(): return "G" print "C.f.author =", C.f.author print "C.f.version =", C.f.version print "C.f() =>", C.f() print "C.g() =>", C.g()
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4