Does Python optimize regexes?

Jason Smith jhs at
Tue Jun 29 13:24:55 CEST 2004

Hi.  I just have a question about optimizations Python does when 
converting to bytecode.

import re
for someString in someListOfStrings:
	if re.match('foo', someString):
		print someString, "matched!"

Does Python notice that re.match is called with the same expression, and 
thus lift it out of the loop?  Or do I need to always optimize by hand 
using re.compile?  I suspect so because the Python bytecode generator 
would hardly know about a library function like re.compile, unlike e.g. 
Perl, with builtin REs.

Thanks much for any clarification or advice.

Jason Smith
Open Enterprise Systems
Bangkok, Thailand
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 264 bytes
Desc: OpenPGP digital signature
URL: <>

More information about the Python-list mailing list