Revised PEP 318 - Function/Method Decorator Syntax

Bernhard Herzog bh at intevation.de
Wed Jun 11 09:07:41 EDT 2003


Duncan Booth <duncan at NOSPAMrcp.co.uk> writes:

> Bernhard Herzog <bh at intevation.de> wrote in 
> news:6qwufsn9un.fsf at salmakis.intevation.de:
> 
> > But then again with decorators I might just as well write
> > 
> > def foo(self) as attributed(my_attr = "bar"):
> >     pass
> > 
> > with attributed defined as e.g.
> > 
> > def attributed(**kw):
> >     def add_attrs(f):
> >         for key, value in kw.items():
> >             setattr(f, key, value)
> >     return add_attrs
> > 
> 
> I doubt this would have the desired effect. Perhaps we should take this as 
> a warning: the proposed syntax seems to lead to people writing code 
> snippets like the one above which would result in foo==None.

Oops, indeed. The nested add_attrs should return f.

> I think the problem may be that the assignment to foo is sufficiently 
> obfuscated that it is too easy to forget its happening, or perhaps it's 
> just that forcing the decorators to work by returning an intermediate 
> function is an extra level of indirection that it would be nice to do 
> without.

I think it's rare that one would actually write decorator functions and
if you do you'll hopefully start with a test cases which will
immediately spot the problem if foo ends up being None. For those who
don't write test cases it should become obvious (well, at least it will
raise an exception) once foo is being called for the first time.

Note also that it's only easy to get wrong if you need to pass arguments
to the decorator function and therefore need one extra level of
indirection.

It seems to me that writing decorator functions is on a more abstract
level than what most Python programmers will do in their day to day
work. In this respect the decorators are similar to meta classes but not
as abstract.

   Bernhar


-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                           http://www.mapit.de/




More information about the Python-list mailing list