If One Line

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Dec 25 22:30:04 EST 2014


JC wrote:

> Hello,
> 
> Is it possible in python:
> 
> if ((x = a(b,c)) == 'TRUE'):
>     print x

Fortunately, no. Assignment as an expression is an anti-pattern and a bug
magnet.

The above is best written as:

if a(b,c) == 'TRUE':
    print 'TRUE'


If you need the result of calling the a() function, possibly because you
also have an else clause:

x = a(b,c)
if x == 'TRUE':
    print x
else:
    print x, 'is not equal to a TRUE string.'


Your subject line is misleading, since this has nothing to do with If. You
*can* write an If one liner:


    if condition() == 'FLAG': print "condition equals flag"


What you can't do is assignment as an expression:


    # None of these work
    if (x = func()) == 'RESULT': ...
    for item in (x = func()) or sequence: ...
    vars = [1, 2, 3, (x = func()), 4]




-- 
Steven




More information about the Python-list mailing list