EuroPython 2011: Raymond Hettinger on Python Tips, Tricks and Idioms

Link: Talk description and video

I couldn't find the slides online but please do link me if you find them, they were a treasure trove of awesome tips and very well laid out!

The talk touched on many things, the following tips are unrelated to each other and in no particular order.


Beware the corner cases of negative slicing -- if you use a variable for slicing there's likely a bug lurking in your code!

mytuple = 1, 2, 3 # Tuple declaration also works without parenthesis

Learn Python the way Guido intended it and indented it :P

for x in reversed(seq): # Better than negative slicing because it's clearer, there's no need to do a double take

for i, x in enumerate(seq): # That's Pythonic! Forget about i in range, seq[i]

for x, y in zip(seqx, seqy)

for/else: a for loop with an else, the else executes if there was no break in the loop, that is, when the loop runs to completion. It's only useful when there is a break (the searching use case).

None is always smaller than everything else, in comparisons.

Sets aren't guaranteed order after being sorted, because __lt__ has been overridden to indicate subsets and supersets.

If you intend to define __lt__ you must also implement the 6 ordering functions.

# Key function:
sorted(s, key=str.lower) # (awesome!)

If a class takes in an iterable, and emits iterables lots of awesome may occur, with the prebuilt tools and other surprising uses (kind of works like pipes and filters).

d = defaultdict(dict)
d[stuff][otherstuff] = "blah"
# as opposed to
d = dict()
d[stuff] = dict()
# etc...

d.update(dict(d))

links

social