473,573 Members | 2,932 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Does Python optimize regexes?

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

import re
for someString in someListOfStrin gs:
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
http://oes.co.th

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFA4VGMm5q EoSbpT3kRAsYpAK ClQmFeamBfDx0vg TVpMc+utgmD/QCcDjpi
edwYF0cRA1V2Bvl qV6y4/l4=
=YMB7
-----END PGP SIGNATURE-----

Jul 18 '05 #1
5 2171
Jason Smith wrote:
Hi. I just have a question about optimizations Python does when
converting to bytecode.

import re
for someString in someListOfStrin gs:
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.


Python puts the compiled regular expressions into a cache. The relevant code
is in sre.py:

def match(pattern, string, flags=0):
return _compile(patter n, flags).match(st ring)

....

def _compile(*key):
p = _cache.get(key)
if p is not None:
return p
....

So not explicitly calling compile() in advance only costs you two function
calls and a dictionary lookup - and maybe some clarity in your code.

Peter

Jul 18 '05 #2
Peter Otten wrote:
Python puts the compiled regular expressions into a cache. The relevant


By the way, re.compile() uses that cache, too:
import re
r1 = re.compile("abc ")
r2 = re.compile("abc ")
r1 is r2

True

Peter
Jul 18 '05 #3
Peter Otten wrote:
Python puts the compiled regular expressions into a cache. The relevant
code is in sre.py:

def match(pattern, string, flags=0):
return _compile(patter n, flags).match(st ring)

...

def _compile(*key):
p = _cache.get(key)
if p is not None:
return p
...

So not explicitly calling compile() in advance only costs you two function
calls and a dictionary lookup - and maybe some clarity in your code.


That cost can be significant. Here's a test case where not precompiling the
regular expression increased the run time by more than 50%:

http://groups.google.com/groups?selm....supernews.com

-Mike
Jul 18 '05 #4
Thanks much to Peter and Michael for the clarification.

Peter Otten wrote:
So not explicitly calling compile() in advance only costs you two function
calls and a dictionary lookup - and maybe some clarity in your code.


The reason I asked is because I felt that re.compile() was less clear:

someRegex = re.compile('sea rchforme')
while something:
theString = getTheString()
if someRegex.searc h(theString):
celebrate()

I wanted to remove someRegex since I can shave a line of code and some
confusion, but I was worried about re.search() in a loop.

The answer is this is smartly handled in Python, as opposed to bytecode
optimizations. Great!

--
Jason Smith
Open Enterprise Systems
Bangkok, Thailand
http://oes.co.th

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFA4jN0m5q EoSbpT3kRAry2AJ 9RQQnHiGiR2S5bv 2CdOpOhMNXOdACe KfyO
a3iZduUZ5qmkOco BOkV3XEQ=
=D+ea
-----END PGP SIGNATURE-----

Jul 18 '05 #5
In article <ma************ *************** ***********@pyt hon.org>,
Jason Smith <jh*@oes.co.t h> wrote:

The reason I asked is because I felt that re.compile() was less clear:

someRegex = re.compile('sea rchforme')
while something:
theString = getTheString()
if someRegex.searc h(theString):
celebrate()

I wanted to remove someRegex since I can shave a line of code and some
confusion, but I was worried about re.search() in a loop.


My reasoning is slightly different. I'm always forgetting with
re.search whether the pattern or string goes first; with re.compile, you
can't fail. Yesterday I fixed a couple of bugs where someone else made
the same error....
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
2644
by: Ben | last post by:
Hi all! I learned Python as part of my university coursework... I enjoyed it. Now I'm just wondering how Python compares with asp, jsp, php and what not?? I don't have slightest knowledge about these languages... Are they more advanced than Python? Can Python be integrated with Dreamweaver? Hope some of you can get me out of confusion...
4
2312
by: ketulp_baroda | last post by:
Hi Does python support MVC architecture? Java has register & notify obsever methods in javax.util . Does python has these functions. If not then how to register the views with the models & how to notify the views that the model has been updated??
9
1632
by: angel | last post by:
Hi Java and cpp support one function name multi function prototype. For example: A: int func1(String s){} int func1(int i){} B: int func1(String s){}
15
2340
by: Claudio Grondi | last post by:
Let's consider a test source code given at the very end of this posting. The question is if Python allows somehow access to the bytes of the representation of a long integer or integer in computers memory? Or does Python hide such implementation details that deep, that there is no way to get down to them? The test code below shows, that...
5
4050
by: Avi Kak | last post by:
Hello: Does Python support a peek like method for its file objects? I'd like to be able to look at the next byte in a disk file before deciding whether I should read it with, say, the read() method. Is it possible to do so in Python? Your answer would be much appreciated.
4
1174
by: Blackbird | last post by:
Hello! I think for i in range(10): <some code that depends on i> is more readable than a while loop with explicit incrementation of i. However, range(10) in the command interpreter obviously returns a list. Is
2
2248
by: ACB | last post by:
I have been trying to get the gdmodule installed and have run into an issue. When I import gd I get the following error. >>> import gd Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/local/lib/python2.3/site-packages/gd.py", line 10, in ? import _gd ImportError: /usr/local/lib/libgd.so.2: Undefined symbol...
4
376
by: George2 | last post by:
Hello everyone, Why visual studio does not optimize constructor in this case? I do not understand what the MSDN mentioned, if use different named object, compiler can not optimize. Why? http://msdn2.microsoft.com/en-us/library/ms364057(vs.80).aspx
9
2588
by: Ed Leafe | last post by:
On Apr 21, 2008, at 1:05 PM, Daniel Fetchinson wrote: Don't most binary distributions include SQLite itself? I installed 2.5.2 on a new WinXP VM, and SQLite is working fine. -- Ed Leafe
0
7781
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7699
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7788
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8066
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6421
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5594
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5292
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3733
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3733
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.