Best practices

enumerate

Sous-utilisé !

>>> liste = ('un', 'deux', 'trois')
>>> for index, val in enumerate(liste):
...     print '%d: %s' % (index, val)
...
0: un
1: deux
2: trois

Generators

Generators

Genexps

>>> iter = (x**2 for x in range(10) if x % 2 == 0)
>>> for el in iter:
...     print el
...
0
4
16
36
64

Iterators

utilisez itertools : compilé en C

islice

>>> import itertools
>>> def starting_at_five():
...     value = raw_input().strip()
...     while value != '':
...         for el in itertools.islice(value.split(),
...                                    4, None):
...             yield el
...         value = raw_input().strip()
...
>>> iter = starting_at_five()
>>> iter.next()
one two three four five six
'five'
>>> iter.next()
'six'
>>> iter.next()
one two
one two three four five six
'five'
>>> iter.next()
'six'

Tee

groupby

with et contextlib

Introduit dans 2.6 mais dispo dans 2.5 avec __future__. Sans with:

>>> f = open(my_file, 'w')
>>> try:
...     f.write('pycon fr, ca roxor')
... finally:
...     f.close()

with et contextlib

Avec with:

>>> from __future__ import with_statement
>>> with open(my_file, 'w') as f:
...      f.write('pycon fr, ca roxor')

contextlib

Création de ses propres contextes: