assignment in if

Roy Smith roy at
Wed May 3 01:41:24 CEST 2006

In article <87iroodnqz.fsf at localhost.localdomain>,
 Gary Wessle <phddas at> wrote:

> Hi
> is there a way to make an assignment in the condition of "if" and use
> it later, e.g.
> nx = re.compile('regex')
> if
>    funCall(text,
> is evaluated twice, I was hoping for something like
> nx = re.compile('regex')
> if x =
>    funCall(text, x))

Personally, I find the C-style idiom you long for to be convenient and 
useful.  That being said, it does not exist in Python, by deliberate design 
decision.  In Python, assignment is not an operator with side effects like 
in C or Java, but a statement.  What you need to do is:

nx = re.compile('regex')
x =
if x:
   funCall(text, x))

The lack of embedded assignments leads to slightly more verbose code in 
situations like this, but on the other hand, it avoids the typical C 
disaster of writing a whole function as a one liner.

More information about the Python-list mailing list