[Python-Dev] method decorators (PEP 318) (original) (raw)

Jack Diederich jack at performancedrivers.com
Mon Mar 29 16:40:27 EST 2004


On Mon, Mar 29, 2004 at 01:47:13PM -0700, Shane Holloway (IEEE) wrote:

grr... spacing didn't quite come out right. Blasted tabs. Let's try this again:

class Example(object): def foo(self, *args) [ synchronized(lock), attributes(author='SWH', protocol=IMyProtocol), myArgumentWireMarshaller, ]: pass # Code goes here def bar(self, *args) [ synchronized(lock), attributes(author='SWH', protocol=IMyProtocol), myArgumentWireMarshaller, ]: pass # Code goes here def baz(self, *args) [ synchronized(lock), attributes(author='SWH', protocol=IMyProtocol), myArgumentWireMarshaller, ]: pass # Code goes here more like: class Example(object): IMyProtocolMethod = [ synchronized(lock), attributes(author='SWH', protocol=IMyProtocol), myArgumentWireMarshaller, ] def foo(self, *args) [methodreturns(float)] + IMyProtocolMethod: pass # Code goes here def bar(self, *args) [methodreturns(str)] + IMyProtocolMethod: pass # Code goes here def baz(self, *args) [methodreturns(int)] + IMyProtocolMethod: pass # Code goes here write IMyProtocolMethod as a decorator instead of a list of decorators:

def IMyProtocol(func): for (decor) in [synchronized(lock), attributes(author='SWH', protocol=IMyProtocol), myArgumentWireMarshaller, ]: func = decor(func) return func

class Example(object): def foo(self, *args) [methodreturns(float), IMyProtocol]: pass def bar(self, *args) [methodreturns(str), IMyProtocol]: pass def baz(self, *args) [methodreturns(int), IMyProtocol]: pass

if you do that a lot, write a helper function

def make_decorator_chain(*decors): def anon_decorator(func): for (decor) in decors: func = decor(func) return func return anon_decorator

IMyProtocol = make_decorator_chain(synchronized(lock), attributes(author='SWH', protocol=IMyProtocol), myArgumentWireMarshaller)

-jackdied



More information about the Python-Dev mailing list