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))

< Back to main >

I was also reminded of some included batteries in the standard modules that I should use more often: heapq (nsmallest() et.al.), bisect (insort() et.al.), functools (partial() et.al.), collections (defaultdict, OrderedDict)

I liked this trickery to iterate over a file in 20-byte pieces:

iter(functools.partial(f.read, 20), '')
#1. Posted by Michael Fötsch (Website) on Sat 09 Jul 2011, 19:26

Cool, thanks for the additional tips! :-) #2. Posted by jpichon (Website) on Sun 10 Jul 2011, 17:52

Video is up, no sign of the slides though -- http://ep2011.europython.eu/conference/talks/python-tips-tricks-and-idioms #3. Posted by Vicky (Website) on Wed 17 Aug 2011, 16:19

Hello! This text is normally hidden with CSS. If you can see this, you'll also see two additional fields with no label on the form. Leave them as is, as those are aimed at catching form-filling spam bots. Thank you!

    Name: (or OpenID Sign in with OpenID)
      Email: (Not published)
        Website:
          Comment:
           

          < Back to main | Up >