If you have been programming in python, you must have often heard phrases like “code like a pythonista” or “idiomatic python”. These phrases basically try to emphasize on “readability counts” philosophy in the Zen of Python. There have been several articles on idiomatic python, but below are seven lesser known tips on writing idiomatic python:
1. Use else to execute code after a for loop ends
>>> for zipcode in zipcodes:
... if len(zipcode) > 5:
... print "Invalid length"
... else:
... print "Valid length"
...
Valid length
2. Use comprehensions
List comprehensions are very popular, but few people know about dict comprehensions and set comprehensions.
List Comprehension
>>> name_dict = {name.fname : name.lname for name in names if name.lname}
Set Comprehension
>>> name_set = {name.fname for name in names if name.lname}
3. Define __str__ in a class to show a human readable representation of the class
>>> class Name:
... def __init__(self, name):
... self.name = name
... def __str__(self):
... return "This class represents a Name"
...
>>> name = Name('john')
>>> print name
This class represents a Name
4. Use a generator to lazily load infinite sequences
5. Use _ as a place holder for data in a tuple that should be ignored
(instance_name, instance_size, _) = get_instance_info(instance_uuid)
6. Use partial to fixate function variables
>>> def long_name(first_name, middle_name, last_name):
... print first_name, middle_name, last_name
...
>>> short_name = functools.partial(long_name, 'john')
>>> short_name('jim', 'jr')
john
jim
jr
7. Use zip and izip to help loop over two collections
>>> number = [1, 2, 3]
>>> number_name = ['one', 'two', 'three']
>>> for num, num_name in zip(number, number_name):
... print num, num_name
...
1 one
2 two
3 three
References:
[1] Writing Idiomatic Python
[2] Advice by Raymond Hettinger