That horrible regexp idiom

Ville Vainio ville at spammers.com
Thu Feb 10 06:55:51 EST 2005


>>>>> "Stephen" == Stephen Thorne <stephen.thorne at gmail.com> writes:

    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?

-- 
Ville Vainio   http://tinyurl.com/2prnb



More information about the Python-list mailing list