Collecting Python insights
July 3rd, 2008 at 7:09 pmI’ve started collecting random insights on Python here. The goal is a single place, accessible online, where I can find answers on topics I’ve struggled with before.
I hope others will find the page helpful as well. If you have comments, leave them here.
Related posts:

July 3rd, 2008 at 9:05 pm
xrange uses less memory, but it is slightly slower, as it needs to generate each value on demand.
Just sayin’.
July 4th, 2008 at 7:40 am
In RandomChunker.chunk(), instead of “return ret”, do “yield ret”. Then, you can:
for chunk in rc.chunk():
print chunk
Cheers,
-Mahadevan.
July 4th, 2008 at 8:21 am
JB:
As this benchmark demonstrates, you are quite wrong. xrange is faster (tried for both large and small LISTSIZE):
July 4th, 2008 at 8:21 am
Mahadevan R:
The “insights” supposes RandomChunk already exists and can’t be modified.
July 4th, 2008 at 9:35 am
Python doesn’t have a reverse builtin but it has a reversed builtin:
for char in reversed(”hello world”):
print char
July 4th, 2008 at 2:45 pm
The example for ‘Dynamic code evaluation’ is a good example of how to use exec, but a bad example of when exec is appropriate.The following code is a much nicer way of achieving the same thing, because it doesn’t involve exec and hence you never have to worry about people feeding it malicious strings:
def make_packet_extract(a, b):
____def foo(packet):
________return ord(packet[a]) + 256 * ord(packet[b])
____return foo
(apologies for the underscores, <pre> didn’t seem to want to do its thing)
A better example for exec might be something where you have to change the actual structure of the method you’re building rather than just values within it - changing ‘and’ to ‘or’ or similar.
July 31st, 2008 at 8:49 am
Function reverse won’t work for UTF8 strings
August 2nd, 2008 at 11:09 am
defaultdict(int) is faster than defaultdict(lambda: 0)