Writing Pythonic Code Part I: A Guide to Idiomatic Python

Writing Pythonic Code Part I: A Guide to Idiomatic Python

With its minimalist, readable syntax that looks like written English, Python is often the first programming language learned by new developers. However, those familiar with other programming languages frequently make the mistake of directly translating statements and syntax from other programming languages into Python. To leverage Python effectively, you must embrace Pythonic code - writing in the clearest, most expressive, and idiomatic style aligned with Python's unique capabilities.

What is PEP 8?

PEP 8 is Python's official style guide. These tips and guidelines are recommended best practices for improving readability and maintenance. PEP 8 covers naming conventions, code layout, spacing, documentation and more. Following PEP 8 ensures your code is standardized and "Pythonic". Go here to read more about it.

Elements of Pythonic Code

The main characteristics and standards for writing Pythonic code include:

  • Readability and simplicity

  • Expressive variable and function names

  • Good organization and clean code structure

  • Leveraging built-in functions like map(), filter(), reduce()

  • Favoring "for" loops instead of "while"

  • List comprehensions over loops

  • Use of generators and iterators

  • Exceptions for error handling

This article will mainly focus on code readability and structure.

Readability

The main reason to advocate for Pythonic code is for its improved readability and clean syntax over other programming languages. It is easier to maintain, resulting in ease of collaboration across teams and less prone to errors and bugs. Here's an example of a loop to print every element of a list in Python and JavaScript.

Python

arr = [1, 2, 3, 4, 5]

for element in arr:
  print(element)

Python follows a declarative style of programming. We simply express we want to loop over the elements without specifying how. It also has a simple syntax, among other benefits such as:

  • No indexing needed

  • Direct access to element value

  • Readable, expressive code

  • Minimal code required

JavaScript

const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

The JavaScript for loop on the other hand follows an imperative style of programming; we are telling the computer step-by-step how to iterate over the array using an index, mutating it on each loop iteration. Differences from Python's code include:

  • More verbose syntax

  • Requires index tracking and accessing (prone to errors and bugs)

  • Visual clutter with syntax

The Pythonic code is simpler, cleaner and more expressive. It directly accesses the array values without needing index access. By leveraging Python's iterators and built-in features like for...in, we write less code that is easier to read and maintain. The Pythonic approach emphasizes simplicity, readability and expressiveness.

Structure

The most striking aspect of Python code is its clean style enforced by the significant whitespace rule - using indentation to organize code blocks instead of braces or keywords. Incorrect indentation leads to errors, so whitespace takes on significant meaning, unlike other languages. This forces a visually pleasing and consistent coding layout.

This code will raise an IndentationError because the last print statement should be indented (wrapped inside of the if statement).

fruits = ['apple', 'cherry', 'banana', 'watermelon']

for fruit in fruits:
    print(fruit)
    if fruit == 'cherry':
    print('my favorite!')

Spaces and indentations are required in Python. Other programming languages such as JavaScript do not have this issue; the console.log() statement could have any indentation and JavaScript will understand the intent as long as the expression is wrapped between curly braces.

const arr = [1, 2, 3];

for (let i = 0; i < arr.length; i++) {
  if (arr[i] == 3){
console.log('my favorite number!')
  }
}

However, it's important to note that although not required, we should indent code to make it more readable and organized. You don't have to do this by hand every time, this is when linters become very helpful.

Tools

Linters that help write Pythonic code:

  • pylint, pycodestyle - for checking PEP 8 compliance

  • black, autopep8 - for automatic formatting as per PEP 8

  • mypy - for static type checking

In the next article of this Pythonic Code series, I will go over loops, list comprehensions, and iterables!