assignment in if
Roy Smith
roy at panix.com
Tue May 2 19:41:24 EDT 2006
In article <87iroodnqz.fsf at localhost.localdomain>,
Gary Wessle <phddas at yahoo.com> 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 nx.search(text):
> funCall(text, nx.search(text))
>
> nx.search(text) is evaluated twice, I was hoping for something like
>
> nx = re.compile('regex')
> if x = nx.search(text):
> 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 = nx.search(text)
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