[Python-ideas] while with as [was: if with as]

Jim Jewett jimjjewett at gmail.com
Wed Mar 7 16:48:05 CET 2007

Scott Dial schrieb:
> Talin wrote:
>> already existing import syntax), it seems to me that we are, in fact,
>> establishing a general rule that:

>>      <keyword> <expression> as <variable>:

>> ...is a common syntactical pattern in Python, meaning 'do something
>> special with expression, and then as a side effect, assign that
>> expression to the named variable for this block."

Rather, assign the result of the do-something.

> these are all just broken versions of an infix assignment operator[1].

Not quite, because the precise do-something is implicit in the keywords.

With "import", you assign the imported module (or object), rather than
the name (string) that was the expression itself.

With "with", you assign the result of the enter call, rather than the
context object itself.

With except, you assign the caught instance, rather than the tuple of
classes that caught it.

By strict analogy, in

    while expr as myvar

myvar should be the result of calling bool(expr).  Fortunately, that
is so useless that people would understand the slight change by
analogy to "and" and "or", which return the full value rather than the
boolean to which it maps.

    while expr as myvar:   # proposal

    while (myvar=expr; bool(myvar)):    # except that we can't have
inline statements

    # current python workaround -- though normally we use object-specific
    # knowlege to keep it from being quite this ugly.
    def _test_and_set(val):
        _indirect[0] = val
        return val
    while _test_and_set(val):

> As for this particular case, it is only useful in a very restricted set
> of expressions and I was only able to find a handful of cases in stdlib
> where I could drop in a "if x as y".

I have wanted it, though not nearly so often as I have wanted it for
the "while" loop.

The workarounds with break/continue or changing to a for-loop always bother me.

That said, I'm still not sure it would be worth the cost, because
people might start trying to write

    while (1,2,3)

and expecting an implicit iteration; the confusion to beginners
*might* outweigh the benefits.


More information about the Python-ideas mailing list