[Python-Dev] PEP 343: Context managers a superset of decorators?

Eric Sumner kd5bjo at gmail.com
Mon Feb 13 11:52:28 CET 2006


On 2/12/06, Josiah Carlson <jcarlson at uci.edu> wrote:
[paragraphs swapped]
> The desire for context managers to have access to its enclosing scope is
> another discussion entirely, though it may do so without express
> permission via stack frame manipulation.

My main point was that, with relatively small changes to 343, it can
replace the decorator syntax with a more general solution that matches
the style of the rest of the language better.  The main change (access
to scopes) makes this possible, and the secondary change (altering the
block syntax) mitigates (but does not remove) the syntax difficulties
presented.  I realize that I made an assumption that may not be valid;
namely, that a new scope is generated by the 'with' statement.  Stack
frame manipulation would not be able to provide access to a scope that
no longer exists.

> Re-read the decorator PEP: http://www.python.org/peps/pep-0318.html to
> understand why both of these options (indentation and prefix notation)
> are undesireable for a general decorator syntax.

With the changes that I propose, both syntaxes are equivalent and can
be used interchangeably.  While each of them has problems, I believe
that in situations where one has a problem, the other usually does
not.

>From this point on, I provide a point-by-point reaction to the most
applicable syntax objections listed in PEP 318.  If you're not
interested in this, bail out now.

In the PEP, there is no discussion of a prefix notation in which the
decorator is placed before the 'def' on the same line.  The most
similar example has the decorator between the 'def' and the parameter
list.  It mentions two problems:

> There are a couple of objections to this form. The first is that it breaks
> easily 'greppability' of the source -- you can no longer search for 'def foo('
> and find the definition of the function. The second, more serious, objection
> is that in the case of multiple decorators, the syntax would be extremely
> unwieldy.

The first does not apply, as this syntax does not separate 'def' and
the function name.  The second is still a valid concern, but the
decorator list can easily be broken across multiple lines.

The main objection to an indented syntax seems to be that it requires
decorated functions to be indented an extra level.  For simple
decorators, the compacted syntax could be used to sidestep this
problem.  The main complaints about the J2 proposal don't quite apply:
the code in the block is a sequence of statements and 'with' is
already going to be added to the language as a compound statement.

  -- Eric


More information about the Python-Dev mailing list