[Python-Dev] PEP318 metaclass approach (original) (raw)
Sean Ross sross at connect.carleton.ca
Sat Mar 27 15:10:06 EST 2004
- Previous message: [Python-Dev] method decorators (PEP 318)
- Next message: [Python-Dev] Last chance!
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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()
- Previous message: [Python-Dev] method decorators (PEP 318)
- Next message: [Python-Dev] Last chance!
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]