[Python-ideas] 'where' statement in Python?

Stephen J. Turnbull stephen at xemacs.org
Wed Jul 21 11:31:13 CEST 2010

Andrey Popp writes:

 > Do class definitions or with-statements represent control flow
 > structures? I think, no (with-statement maybe).

In both cases, yes.  From the point of view of the programmer writing
the controlled suite, they're very simple control structures (serial
execution).  True, the important thing that a class definition does is
set up a special configuration of namespaces in which the suite is
executed (eg, instead of def registering a function in the global
namespace, it registers it in the class).  Nevertheless, it does
determine control flow, and the statements in a class "declaration"
are executed at runtime, not at compile time.  The with statement is a
nontrivial control flow structure: it ensures that certain code is
executed at certain times, although the code that it provides
guarantees for is not in the explicit suite it controls.

Antoine's point here is not that "given" isn't a control flow
*structure*.  It is that it is not a *statement*, but rather a
fragment that can be added to a wide variety of statements.  That is
quite a major departure for Python, though I think it a natural one in
this context.

Antoine might find

    value = a*x*x + b*x + c
    a = compute_a()
    b = compute_b()
    c = compute_c()

less objectionable on those grounds.  Ie, it is now a proper control
statement.  I hasten to add that I think this syntax is quite horrible
for *other* reasons, not least needing to find two keywords.  Worst,
"given" advocates want the computation of a, b, and c subordinated
lexically to computation of value, but here they are on the same level.

 > Consider the following:
 > ...
 > value = a*x*x + b*x + c given:
 >     a = compute_a()
 >     b = compute_b()
 >     c = compute_c()
 > ...
 > which is roughly equivalent to
 > ...
 > a = compute_a()
 > b = compute_b()
 > c = compute_c()
 > value = a*x*x + b*x + c
 > ...
 > with two differences:
 > - It emphasizes that `value` is a target of this computation and `a`,
 > `b` and `c` are just auxiliary.
 > - It states that `a`, `b` and `c` are only used in statement, before
 > the `given` keyword, that would help future refactorings.
 > Due to the second point, it can't be considered as syntactic sugar.

But the second point doesn't prove you can't get the same semantics,
only that a naive implementation fails.  If you want to ensure that
`a`, `b` and `c` are only used in a limited scope, there's always

def compute_quadratic(z):
    a = compute_a()
    b = compute_b()
    c = compute_c()
    return a*x*x + b*x + c
value = compute_quadratic(x)
del compute_quadratic

Now *that* is quite ugly (and arguably unreadable).  But it shows that
there are other ways of obtaining the same semantics in Python, and
thus "given" is syntactic sugar (at least for this use case).

More information about the Python-ideas mailing list