[Python-Dev] 2.4a2, and @decorators

Phillip J. Eby pje at telecommunity.com
Tue Aug 3 17:00:41 CEST 2004


At 07:32 AM 8/3/04 -0700, Guido van Rossum wrote:
> > In practical terms, all this means is that I'll just use the hacked
> > syntax until I no longer need to support Python 2.3.
>
>I don't understand why you prefer your hack over the established way
>to do decorators pre-2.4, which is
>
>   def foo(): ...
>   foo = staticmethod(foo)

For the same reason that PEP 318 was written in the first place: to improve 
readability.


>This works across releases (including IronPython), doesn't require any
>magic, is documented, etc.

True; and most of my existing decorator-using code works this way, and I 
don't plan on rushing out to change any of it any time soon.


>   Isn't that much
>better than spending effort on hacks based on sys.settrace (which are
>surely going to produce bafflement from users who aren't familiar with
>that implementation hack)?

Well, up until recently, I thought the [] syntax was still a shoo-in and 
that the settrace hack was just going to be a way to write 
backwards-compatible code.

In the meantime, I've implemented a predicate-dispatch generic function 
system using the settrace hack for PyProtocols 1.0, and don't want to have 
to put off using it until 2.4.  (FWIW, I still support 2.2.2, so "until 
2.4" means maybe 1-2 years for me.)  It looks like this:

     [when("isinstance(x,Foo) and y>23")]
     def do_something(x,y):
          # code for when x is a Foo and y>23

     [when("isinstance(x,Bar) and y<99")]
     def do_something(x,y):
          # code for when x is a Bar and y<99

Rendered without any decorator syntax, it would have to be something like:

     def do_something_x_Foo_y_gt_23(x,y):
          # code for when x is a Foo and y>23

     do_something.add("isinstance(x,Foo) and y>23", do_something_x_Foo_y_gt_23)

     def do_something_x_Bar_y_lt_99(x,y):
          # code for when x is a Bar and y>99

     do_something.add("isinstance(x,Bar) and y>23", do_something_x_Bar_y_lt_99)

...which is a significant loss in readability.

Now, it's true that this will just become '@when("whatever")' in 2.4, and 
I'm *fine* with that, just disappointed that the syntax won't be forward 
compatible.

Indeed, what I'd rather focus on is making sure that the *semantics* will 
be forward compatible.  Which I think they will be.  What I'll probably do 
is make 'when()' and other decorators return a callable that deactivates 
the trace hack as a side effect of performing the decoration.  That way, 
[when()] and @when() can coexist in a code base during the migration period.



More information about the Python-Dev mailing list