How to do this in Python...

Peter Hansen peter at
Fri Jan 24 16:06:54 CET 2003

Michael Tiller wrote:
> I'm puzzled by what seems like a missing piece of functionality in Python.
> In C++, I could write a statement like this:
> if (match=re.match(pattern, string))
>   // do something with the match object
> But I cannot figure out how to do the equivalent thing in Python.  The idea
> here is to have an assignment statement within an if statement so that I
> don't have to call match twice or obfuscate the code.  It seems to me that
> my current options are:
> match = re.match(pattern, string)
> if match:
>   // do something with match object
> -or-
> if re.match(pattern, string):
>     match = re.match(pattern, string)
> The first one seems unnecessarily verbose and the second one is inefficient.
> Are there any other options?

Yes, the third option is this: get rid of the urge to do this, and
the belief that it is a good idea.

Such structures have long been fertile ground for bugs in C and
its children, and reduce the readability of code.  The "functionality"
you want is actually a deprecated feature in some companies, where
assignment-tests like that are outlawed in if/for/while statements.

If you can start to think in this style, your code will become more
readable and you'll have fewer concerns about "missing" functionality
in Python.


More information about the Python-list mailing list