473,788 Members | 2,800 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 2183
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
2674
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
2329
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
1639
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
2353
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 extracting bits from an integer value n is faster when using n&0x01 than when using n%2 and I...
5
4060
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
1182
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
2255
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 "libiconv_open"
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
2637
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
9498
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10364
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10110
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.