[Python-ideas] Reuse "for" to express "given"

Steven D'Aprano steve at pearwood.info
Thu May 24 14:10:34 EDT 2018


On Thu, May 24, 2018 at 11:54:09AM -0400, Alexander Belopolsky wrote:
> I have read most of the PEP 572 related threads, but I don't think I've
> seen this idea.  As many other people mentioned, Python already allows a
> trick to introduce local bindings in generator expressions and list
> comprehensions.  This can be achieved by adding a "for var in [<expr>]"
> clause.  I propose to make "for var = <expr>" have the same effect as "for
> var in [<expr>]".

C is well known for encouraging the "assignment instead of equals" error 
when people mistakenly use = when they mean ==. Instead of copying this 
design flaw, we'll have our own infamous design flaw: "assignment 
instead of looping" errors, when we mistakenly type "for var = thing" 
instead of "for var in thing" (or vice versa).

Who says Python never innovates? :-)



[...]
> [(x, y, x/y) for x in data for y = f(x) if y]

[(x, y, x/y) for x in data if y := f(x)]


In another post, you wrote:

    Yes, for people with a C/C++ background, "for" may be too
    strongly associated with loops, but in mathematical sense,
    it seems clear that "for var in a set" means iteration
    over a set, while "for var = expression" means binding to
    a single value.

I don't come from a C/C++ background. I think "for" is strongly 
associated with loops in a large number of programming languages, 
including Python.

http://rosettacode.org/wiki/Loops/For

But I do have a mathematics background, and I don't remember ever seeing 
"for x = value" used in the sense you mean. I certainly wouldn't write 
that myself. I would expect to either:

    Given x = expression, then

    equation including x


or the reverse order:

    equation including x

    where x = expression


Normally I would only use "for" either in the context of sums, or the 
"for all" ∀ quantifier. (If that symbols doesn't show up, it is an 
upside down A.)


-- 
Steve


More information about the Python-ideas mailing list