How to be a happy programmer (with Python) ? 1/3

I’ve just watched Hillary Mason’s talk in Pycon 2011 :
And that got me thinking about all the python constructs that makes my day better, and i decided to make a list of them and their meaning.

  • With

The with keyword is the equivalent of the whole try, catch, finally triplets in Java to handle resources (files, database connections, remote connections, anything that can fail). So the with statement is here to make sure that, for example using a database connection, transaction is started and stopped correctly and can be used as follow :

with open('/tmp/my_file', 'w') as p:
     p.write('Writing in a properly closed file resource.')

For a few more example python-with-statement, the official presentation for What’s new in 2.5 and if you want to know more in order to implement objects usable with the « with » statement, you need to see how the context managers work

  • List comprehensions

I shouldn’t even have to explain how much joy you can gain from using these, especially when you’re dealing with object oriented programming or immutable objects, well pretty much anytime you need to operate simple transformation on Lists, dictionnaries, anything iterable, list comprehension is not only the most beautiful way, but also many times, the most efficient way. So here we go for an example :

>>> words = 'The quick brown fox jumps over the lazy dog'.split()
>>> print words
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
>>> stuff = [[w.upper(), w.lower(), len(w)] for w in words]
>>> for i in stuff:
...     print i
['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]

This was the first part of 3 showing  the few Python syntax constructs that makes me « not » scream when i try to do things and i don’t want to lose time ! See you next time.



Votre commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:


Vous commentez à l’aide de votre compte Déconnexion /  Changer )

Photo Facebook

Vous commentez à l’aide de votre compte Facebook. Déconnexion /  Changer )

Connexion à %s

%d blogueurs aiment cette page :