How to Write Pythonic Code

Saad Afzal

Saad Afzal

· 2 min read
Pythonic code. How to write it?

What Is PEP8 in Python?

Python is a flexible language with few restrictions on formatting, which is where PEP8 comes in. PEP8 is a style guide that provides guidelines to ensure your code is readable and maintainable. Consistently following PEP8 makes your code easier to understand and helps in collaborative environments.

Using Tools to Enforce PEP8

Linters like Flake8 and Pylint can automatically spot issues before you push your code, saving review time. Libraries like Black can even auto-format your code. Integrate these tools into your IDE (e.g., VS Code) and CI/CD pipeline for seamless adherence to PEP8.

6 Python Features to Write Pythonic Code

1. Value Swapping and Multiple Assignment

Python allows you to swap values easily without a temporary variable:

a, b = 1, 2
a, b = b, a

You can also unpack lists:

fruits = ["apple", "banana"]
f1, f2 = fruits
# f1 = "apple", f2 = "banana"

2. Passing Multiple Arguments (*args and **kwargs)

Python enables functions to accept variable numbers of arguments using *args and **kwargs:

def calculate(*values):
return sum(values)

print(calculate(1, 2, 3, 4)) # Output: 10

def build_house(**rooms):
for room, num in rooms.items():
print(f"{room}: {num}")

build_house(bedroom=2, kitchen=1)
# Output:
# bedroom: 2
# kitchen: 1

3. Comprehension

Comprehensions offer a concise way to create lists, sets, and dictionaries:

squares = [x**2 for x in range(10)]
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

4. Underscores

Underscores in Python have special meanings:

• Single leading underscore: _var (private variable)
• Double leading underscore: __var (name mangling)
• Double leading and trailing underscores: __init__ (magic method)


class House:
def __init__(self, area):
self.area = area

def __repr__(self):
return f"House with {self.area} square meters"

house = House(120)
print(house) # Output: House with 120 square meters

5. Context Manager

Context managers handle resource management (like file operations) efficiently:

with open("data.txt", "r") as file:
content =

You can create custom context managers using __enter__ and __exit__ methods:

class DatabaseHandler:
def __enter__(self):
print("Start Database")

def __exit__(self, exc_type, exc_value, traceback):
print("Stop Database")

with DatabaseHandler():
print("Backing up database")
# Output:
# Start Database
# Backing up database
# Stop Database

6. Generators

Generators allow you to iterate over data without storing the entire dataset in memory:

def generate_squares(n):
for i in range(n):
yield i**2

for square in generate_squares(5):
# Output: 0, 1, 4, 9, 16

By understanding and applying these 6 Python features, you can write more Pythonic, efficient, and maintainable code. Thats a wrap, stay tuned for more pythonic content...

Saad Afzal

About Saad Afzal

With a Master's degree in Structural Engineering, I began my journey in engineering consultancy, where I discovered my passion for automation and software development. As I delved deeper, I integrated Python scripts into my workflows, revolutionising structural design and analysis.

Driven by a desire to embrace the scalability of web applications, I transitioned into full-stack development and cloud engineering. Through relentless self-study, I honed my skills and collaborated with esteemed organizations to develop cutting-edge solutions. Today, I specialize in architecting robust systems and leveraging cloud technologies to create scalable, secure, and user-centric applications.

Copyright © 2024 CodingStruct. All rights reserved.
Made by Saad Afzal· Github