That horrible regexp idiom

S

Stephen Thorne

Hi,

import re
foo_pattern = re.compile('foo')

'>>> m = foo_pattern.search(subject)
'>>> if m:
'>>> pass
'>>> else:
'>>> pass


We've all seen it before. Its a horrible idiom that you would achieve
in another language by doing:

if (m = foo_pattern.search(subject))
{ }
else
{ }

but it occured to me today, that it is possible to do it in python
without the extra line.
'
'>>> def xsearch(pattern, subject):
'>>> yield pattern.search(subject)

'>>> for m in xsearch(foo_pattern, subject):
'>>> pass
'>>> else:
'>>> pass

simple, concise, requires no new syntax, and is only a little confusing[1]!

Just recording some thoughts I had. This still doesn't take care of
the horrors of chaining multiple regular expressions. The following is
still incredibly hideous.

'>>> for m in xsearch(foo_pattern, subject):
'>>> pass
'>>> else:
'>>> for m in xsearch(bar_pattern, subject):
'>>> pass
'>>> else:
'>>> pass

Thankyou for your time.

Stephen Thorne

[1] Actual confusement may vary.
 
A

alex23

Stephen said:
We've all seen it before. Its a horrible idiom that you would achieve
in another language by doing:

if (m = foo_pattern.search(subject))
{ }
else
{ }

but it occured to me today, that it is possible to do it in python
without the extra line.

'>>> for m in xsearch(foo_pattern, subject):
'>>> pass
'>>> else:
'>>> pass

simple, concise, requires no new syntax, and is only a little
confusing[1]!

It won't have quite the same effect though, as the 'else' statement is
*always* called after the 'for' loop completes.

To have the functionality you're after, you need to include a break in
the code block within the loop.

- alex23
 
V

Ville Vainio

Stephen> We've all seen it before. Its a horrible idiom that you
Stephen> would achieve in another language by doing:

Stephen> if (m = foo_pattern.search(subject))
Stephen> { }
Stephen> else
Stephen> { }

Stephen> but it occured to me today, that it is possible to do it in python
Stephen> without the extra line.
Stephen> '
Stephen> '>>> def xsearch(pattern, subject):
Stephen> '>>> yield pattern.search(subject)

Stephen> '>>> for m in xsearch(foo_pattern, subject):
Stephen> '>>> pass
Stephen> '>>> else:
Stephen> '>>> pass

Stephen> simple, concise, requires no new syntax, and is only a
Stephen> little confusing[1]!

I'm always confused by for-else (lack of practice), but isn't the else
clause going to be always executed when there is no break in the for
suite?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top