Ifs and assignments

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jan 2 22:33:59 EST 2014


Dennis Lee Bieber wrote:

> On Thu, 02 Jan 2014 17:20:54 +0000, John Allsup <pydev at allsup.co>
> declaimed the following:

>>In many languages, such as C, one can use assignments in conditionals
>>and expressions.  The most common, and useful case turns up when you
> 
> Really? You can't do it in FORTRAN, BASIC, COBOL, Pascal, Ada...
> 
> C, C++, Java, C# are all based on the same core syntax. For all
> effective purposes, they are the same as grouping M$ Visual BASIC,
> GW-BASIC, Kemeny&Kurtz TrueBASIC as "most languages, such as BASIC"...


Thank you for pointing this out! Far too many people imagine that C and the
C-inspired languages make up the entire universe of programming.

But having said that, features should be judged on their merit, not on
whether they are familiar to Ada/Lisp/C/Algol/... programmers. (Although
familiarity is one factor out of many which should be considered.)

Personally, I find it hard to care about assignment as an expression. I find
the obvious C-inspired syntax terrible, as it is too easy to mistakenly use
== instead of = or visa versa:

if m = re.match(pattern, text):
    ...

Using "as" is slightly better:

if re.match(pattern, text) as m:
    ...

but I don't think it's sufficiently useful for me to get excited about it.

However, I don't think we should treat this as specific to if statements:

    for i, obj in enumerate(alist + blist + clist as items):
        items[i] = process(obj)


Is that really better than this?

    items = alist + blist + clist
    for i, obj in enumerate(items):
        items[i] = process(obj)



-- 
Steven




More information about the Python-list mailing list