DEV Community

Kuldeep Singh
Kuldeep Singh

Posted on

How to Write Python Code in a Pythonic Way

Python is one of the most popular and powerful programming languages. It's widely used for various purposes such as web development, data analysis, machine learning, automation, etc. It is also known for its simplicity, readability, and expressiveness.

However, writing Python code is not just about following the syntax and semantics of the language. It is also about following the style and culture of the Python community. This is what we call writing Python code in a Pythonic way.

Writing Python code in a Pythonic way means following the best practices and idioms of the Python language that make your code more readable, elegant, and efficient. It also means taking advantage of the features and options that Python offers to make your code more concise and expressive.

In this blog post, I will share with you some tips and examples on how to write Python code in a Pythonic way, based on the official Style Guide for Python Code and some online resources. Let’s get started!

General Writing Style

One of the first things to consider when writing Python code is the general writing style. This includes how to format your code, how to name your variables and functions, how to use whitespace and indentation, how to write comments and docstrings, etc.

Use 4 spaces per indentation level.

# Bad practice
def foo():
  print("Hello")
    print("World")

# Good practice
def foo():
    print("Hello")
    print("World")
Enter fullscreen mode Exit fullscreen mode

Limit all lines to a maximum of 79 characters.

# Bad practice
print("This is a very long line of code that exceeds the recommended limit of 79 characters")

# Good practice
print("This is a very long line of code that "
      "exceeds the recommended limit of 79 characters")
Enter fullscreen mode Exit fullscreen mode

Use blank lines to separate functions and classes, and larger blocks of code inside functions.

# Bad practice
def add(x, y):
    return x + y
def subtract(x, y):
    return x - y
def multiply(x, y):
    return x * y
def divide(x, y):
    return x / y

# Good practice
def add(x, y):
    return x + y


def subtract(x, y):
    return x - y


def multiply(x, y):
    return x * y


def divide(x, y):
    return x / y

Enter fullscreen mode Exit fullscreen mode

Use lowercase letters for variables and functions, and uppercase letters for constants. Use underscores to separate words in names.

# Bad practice
MyVariable = 10 # variable name should be lowercase
myFunction() # function name should be lowercase
my constant = 20 # constant name should be uppercase

# Good practice
my_variable = 10 # variable name is lowercase
my_function() # function name is lowercase
MY_CONSTANT = 20 # constant name is uppercase
Enter fullscreen mode Exit fullscreen mode

Use descriptive names for variables and functions that reflect their purpose and meaning. Avoid using single letters or ambiguous names.

# Bad practice
x = 10 # what does x represent?
f() # what does f do?
n = 20 # what does n represent?

# Good practice
length = 10 # length is descriptive
area(length, width) # area is descriptive
is_prime(number) # is_prime is descriptive
Enter fullscreen mode Exit fullscreen mode

Use docstrings to document your functions and classes.

def area(length, width):
    """Return the area of a rectangle.

    Parameters:
    length (float): The length of the rectangle.
    width (float): The width of the rectangle.

    Returns:
    float: The area of the rectangle.
    """
    return length * width

help(area) # displays the docstring
area.__doc__ # returns the docstring
Enter fullscreen mode Exit fullscreen mode

Use comments to explain your code when necessary.

# Bad practice
x = 10 # assign 10 to x
y = x + 5 # add 5 to x and assign to y
print(y) # print y

# Good practice
x = 10 # initial value
y = x + 5 # increment by 5
print(y) # display result
Enter fullscreen mode Exit fullscreen mode

By following these general writing style guidelines, you will make your code more consistent, clear, and easy to read.

Using Variable Tricks

Python offers many options that allow you to write simple and expressive commands containing variable assignment operations. Here are some of the tricks you can use to make your code more Pythonic:

Swap two variables without using a temporary variable.

# Bad practice
temp = x
x = y
y = temp

# Good practice
x, y = y, x
Enter fullscreen mode Exit fullscreen mode

Assign multiple variables in one line.

# Bad practice
x = 1
y = 2
z = 3

# Good practice
x, y, z = 1, 2, 3
Enter fullscreen mode Exit fullscreen mode

Unpack a sequence into multiple variables.

# Bad practice
my_list = [1, 2, 3]
x = my_list[0]
y = my_list[1]
z = my_list[2]

# Good practice
my_list = [1, 2, 3]
x, y, z = my_list
Enter fullscreen mode Exit fullscreen mode

Use the asterisk (*) operator to collect or unpack variable numbers of arguments.

# Bad practice
def add(a, b):
    return a + b

def add_many(*args):
    result = 0
    for arg in args:
        result += arg
    return result

# Good practice
def add(*args):
    return sum(args)

add(1, 2) # returns 3
add(1, 2, 3) # returns 6
add(1, 2, 3, 4) # returns 10
Enter fullscreen mode Exit fullscreen mode

By using these variable tricks, you will make your code more concise and expressive.

Dealing With Lists

Lists are one of the most common and versatile data structures in Python. They can store any type of objects and support various operations such as indexing, slicing, appending, extending, inserting, removing, sorting, reversing, etc. Here are some of the tips and tricks you can use to deal with lists in a Pythonic way:

Use list comprehensions to create new lists from existing iterables.

# Bad practice
squares = []
for x in range(10):
    squares.append(x**2)

# Good practice
squares = [x**2 for x in range(10)]
Enter fullscreen mode Exit fullscreen mode

Use the in operator to check if an element is in a list.

# Bad practice
found = False
for x in my_list:
    if x == target:
        found = True
        break

# Good practice
found = target in my_list
Enter fullscreen mode Exit fullscreen mode

Use the enumerate function to loop over a list with indexes.

# Bad practice
index = 0
for x in my_list:
    print(index, x)
    index += 1

# Good practice
for index, x in enumerate(my_list):
    print(index, x)
Enter fullscreen mode Exit fullscreen mode

Use the zip function to loop over multiple lists in parallel.

# Bad practice
for i in range(len(names)):
    print(names[i], ages[i])

# Good practice
for name, age in zip(names, ages):
    print(name, age)
Enter fullscreen mode Exit fullscreen mode

By using these tips and tricks, you will make your code more efficient and elegant when dealing with lists.

Having Fun With Functions

Functions are one of the most important and powerful features of Python. They allow you to group and reuse code, improve readability and modularity, and implement abstraction and encapsulation. Here are some of the ways you can have fun with functions and make your code more Pythonic:

Use default arguments to provide optional parameters to your functions.

# Bad practice
def greet(name):
    if name:
        print(f"Hello, {name}!")
    else:
        print("Hello, world!")

# Good practice
def greet(name="world"):
    print(f"Hello, {name}!")
Enter fullscreen mode Exit fullscreen mode

Use keyword arguments to provide named parameters to your functions.

# Bad practice
def area(length, width):
    return length * width

area(10, 5) # returns 50

# Good practice
def area(length, width):
    return length * width

area(width=5, length=10) # returns 50
Enter fullscreen mode Exit fullscreen mode

Use lambda functions to create anonymous functions.

# Bad practice
def square(x):
    return x**2

my_list = [1, 2, 3]
squares = map(square, my_list)

# Good practice
my_list = [1, 2, 3]
squares = map(lambda x: x**2, my_list)
Enter fullscreen mode Exit fullscreen mode

Use decorators to modify or enhance the behavior of your functions.

# Bad practice
def hello():
    print("Hello")

def log(func):
    def wrapper():
        print(f"Calling {func.__name__}")
        func()
        print(f"Done calling {func.__name__}")
    return wrapper

hello = log(hello)
hello()

# Good practice
def log(func):
    def wrapper():
        print(f"Calling {func.__name__}")
        func()
        print(f"Done calling {func.__name__}")
    return wrapper

@log
def hello():
    print("Hello")

hello()
Enter fullscreen mode Exit fullscreen mode

By using these ways, you will make your code more fun and flexible when using functions.

Follow the Zen of Python

The Zen of Python is a collection of 19 principles that guide the design of the Python language. They are written by Tim Peters, one of the core developers of Python, and can be accessed by typing import this in the Python interpreter. Here are some of the most important ones for writing Pythonic code:

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • There should be one-- and preferably only one --obvious way to do it.
  • If the implementation is hard to explain, it’s a bad idea.
  • If the implementation is easy to explain, it may be a good idea.

By following these principles, you will make your code more beautiful and Pythonic.

I'll be updating this story weekly basis with the best Pythonic way to write Python code so don't forget to save it.

You can find me on Twitter, LinkedIn, and Website

Top comments (0)