Python: any() + generator expression

Here's a nice use of any() with a generator expression:
    def is_url_interesting(self, url):
return any(regex.match(url) for regex in self.interesting_url_regexes)
It's fast because any() shortcircuits the same way "or" does. It's way shorter than the comparable "for" loop. Last of all, I think it's very readable, at least if you're used to reading list comprehensions.


Anonymous said…
And what does then self.interesting_url_regexes include? I'm pretty new to python, I would go for this one like:

any(re.match(regex, url) for regex in self.interesting_url_regexes)
Anonymous said…
self.interesting_url_regexes would include compiled regex objects.

regex = re.compile(regex_string)

since you would probably want to use the function more than once, it would make sense to pre-compile the regex and save time.
Unknown said…
Save time when? They get compiled in any case the first time they are used, and (C)Python caches previously used regexes, so there is actually no advantage to explicitly compiling them except that it arguably makes for better readability in this case.
jjinux said…
I always thought that cPython cached compiled regexes too. However, at some point, I was reading a Python book that showed the time difference. Now I'm just confused.
Dave Kirby said…
If you read the source to the re module, you can see the code that does the caching. It caches up to 100 regex, then on the 101st regex it blows the cache away and starts again with an empty cache.

If you have >100 regex then it is definitely worth pre-compiling them. If you have less then you still save some time by precompiling since you do not need to do the cache lookup on each match.

The source for 2.5.2 is at

The relevant code is in the _compile function.
jjinux said…
Awesome comment, Dave. Thanks for finally clearing it up ;)
Justin A said…
Even faster would be to '|'.join the regexes together and match on that one.
jjinux said…
> Even faster would be to '|'.join the regexes together and match on that one.

I know that that's true for certain regular expression engines, but are you sure it's true for Python's?
Bram said…
randomly bumped into your post... imho even nicer would be to use map instead of the for-loop:

return any(map(regex.match, self.interesting_url_regexes))

- bram
jjinux said…
+1 for map :)