Writing Idiomatic Python

“Idiomatic” (or “Pythonic”) code is a practice of coding that makes use of conventions that the Python community has generally accepted as correct.

But who decides what the accepted way is? This could be mandated by PEP and most usually just a natural consensus the community arrives at.

Now, how do we know if a particular piece of code is idiomatic? First, it can be determined through the Python documentation. This contains mostly everything about the function, variables, etc. and how they should be used. Second, it can be determined by reading codes from other famous repositories. There are a lot of repositories out there, like in Github, that are written idiomatically and one good example is the requests. Lastly, it can be determined by writing code and getting feedback from experienced developers. Just like the saying goes, practice makes perfect.

So why is writing idiomatic Python so important? There are only three main things and these are: readability, maintainability and correctness. When we say readability, think about how others can easily understand your code. For maintainability, it is how others can easily make changes to your code. And for correctness, it is how others can easily detect bugs just by reading your code. But always take note that the others includes yourself. Why? Imagine yourself revisiting a project that you have worked on for the past three years. I am pretty sure you won’t remember why it was written that way. And if the code wasn’t written idiomatically, you will have to read and trace the codes again to understand why it was written that way. This can be a pain in the ass as it takes up most of your time.

Here are some sample codes that will show you how to write Python idiomatically.

1. Avoid repeating variable name in compound if statement.

Harmful

is_generic_name = False
name = 'Tom'
if name == 'Tom' or name == 'Dick' or name == 'Harry':
  is_generic_name = True

Idiomatic

name = 'Tom'
is_generic_name = name in ('Tom', 'Dick', 'Harry')

2. Use the enumerate function in loops instead of creating an “index” variable.

Harmful

my_container = ['Larry', 'Moe', 'Curly']
index = 0
for element in my_container:
  print('{} {}'.format(index, element))
  index += 1

Idiomatic

my_container = ['Larry', 'Moe', 'Curly']
for index, element in enumerate(my_container):
  print('{} {}'.format(index, element))

3. Use predefined functions instead of calculating them manually.

Harmful

def calculate_mean(value_list):
  sum = 0
  for value in value_list:
      sum += value
  return float(sum / len(value_list))

print calculate_mean([1, 2, 3, 4]

Idiomatic

# python2
def calculate_mean(value_list):
  return float(sum(value_list) / len(value_list))
print calculate_mean([1, 2, 3, 4]
# python3
import statistics

print (statistics.mean([1, 2, 3 ,4])

4. Follow the docstring conventions described in PEP-257.

Harmful

def calculate_statistics(value_list):
  # calculates various statistics for a list of numbers
 
   <The body of the function>

Idiomatic

def calculate_statistics(value_list):
  """
  Return a tuple containing the  mean, median,
  and mode of a list of integers
   
  Arguments:
  value_list -- a list of integer values
  """
  <The body of the function>

These are just some of the few code samples. You can check the book “Writing Idiomatic Python” by Jeff Knupp to see gain more insight.

Writing idiomatic codes does not only apply to Python but also to other programming languages. Always keep in mind that the codes should be written idiomatically based on their own standards. You don’t want to have Python codes written as if they were Java. Python developers would have difficulty reading them and that just isn’t efficient.

So when writing your codes, just remember this quote by John Woods: “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”

Blog Posts by Lorence Lim


Related Entries