A curious bit of code...

forman.simon at gmail.com forman.simon at gmail.com
Fri Feb 14 15:04:02 EST 2014


On Thursday, February 13, 2014 7:26:48 PM UTC-8, Ned Batchelder wrote:
> On 2/13/14 9:45 PM, forman.simon at gmail.com wrote:
> 
> > For the record I wasn't worried about the performance.  ;-)
> 
> >
> 
> > It was for Tkinter event strings not markup tags.
> 
> >
> 
> > I'm glad this was the time winner!
> 
> >
> 
> > "key and key[0] == '<' and key[-1] == '>'"
> 
> >
> 
> >
> 
> > Cheers to the folks who did the timings (and saved me from the trouble!)
> 
> >
> 
> > Last but not least...  s[::len(s)-1]   omg!!?   ;-D
> 
> >
> 
> 
> 
> If you aren't worried about performance, why are you choosing your code 
> 
> based on which is the fastest?  There are other characteristics 
> 
> (clarity, flexibility, robustness, ...) that could be more useful.


I guess I'm taking the word "worried" a little too seriously.

Back story: I am hoping to contribute to IDLE and am reading the code as a first step.  I came across that line of code (BTW, I was wrong: it is NOT processing Tkinter event strings but rather special "<pyshell#...> entries" in linecache.cache [1]) and had to resist the urge to change it to something more readable (to me.)  But when I thought about it I wasn't able to discern if any of the new versions would actually be enough of an improvement to justify changing it.

To be clear: I have no intention of modifying the IDLE codebase just for fairly trivial points like this one line.

The most satisfying (to me) of the possibilities is "if key and key[0] == '<' and key[-1] == '>':" in the dimensions, if you will, of readability and, uh, unsurprising-ness, and so I was pleased to learn that that was also the fastest.


(FWIW, it seems to me that whoever wrote that line was influenced by shell programming.  It's a shell sort of a trick to my eye.)


When writing Python code I *do* value "clarity, flexibility, robustness" and almost never worry about performance unless something is actually slow in a way that affects something..

Warm regards,
~Simon


[1] http://hg.python.org/cpython/file/3a1db0d2747e/Lib/idlelib/PyShell.py#l117



More information about the Python-list mailing list