How to do this in Python...

Bengt Richter bokr at oz.net
Thu Jan 23 18:14:34 EST 2003


On Thu, 23 Jan 2003 16:40:02 -0500, "Michael Tiller" <mtiller at ford.com> wrote:

>I'm puzzled by what seems like a missing piece of functionality in Python.
>I suspect there is a simple way to do what I want to do and I'm guessing
>someone here can point it out to me.  Here is the issue:
>
>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?
>
You could use a callable object to save the value and also immediately return it, e.g.,

 >>> class Holder:
 ...     def __init__(self): self.args = ()
 ...     def __call__(self, *args):
 ...         if args: self.args=args
 ...         if len(self.args)==1: return self.args[0]
 ...         return self.args
 ...
 >>> h = Holder()

 >>> import re
 >>> if h(re.match(r'(\d+)', '123dfgdfg456')): print h().groups()
 ...
 ('123',)
 >>> if h(re.findall(r'(\d+)', 'asda123dfgdfg456')): print h()
 ...
 ['123', '456']
 >>> if h(re.findall(r'(\d+)', 'asdaXXXdfgdfgXXX')): print h()
 ...
 >>>

or you can abuse a list comprehension side effect wart (IMO) to create a local
binding while having the expression evaluate to the thing you want, for the if test:

 >>> if [m for m in [re.findall(r'(\d+)', 'asda123dfgdfg456')]][0]: print m
 ...
 ['123', '456']
 >>> if [m for m in [re.findall(r'(\d+)', 'asdaXXXdfgdfg456')]][0]: print m
 ...
 ['456']
 >>> if [m for m in [re.findall(r'(\d+)', 'asdaXXXdfgdfgXXX')]][0]: print m
 ...
 >>>

You might also want to look at passing a function to re.sub in place
of a replacement pattern, to have your function get called with
match objects. See re module docs.

Regards,
Bengt Richter




More information about the Python-list mailing list