Skillversitas

Tips & Tricks

"Pythonic" code is code that leverages Python's unique features in an idiomatic and elegant way. Here are several techniques every programmer should know.

Writing Pythonic code is not just about aesthetics — it makes code easier to read and maintain, with fewer bugs. Python is designed with the philosophy "There should be one — and preferably only one — obvious way to do it." Mastering Python idioms means you write code that is natural for the language, not a translation from another language like Java or C++.

Features like comprehensions, generators, decorators, context managers, and unpacking are powerful tools. But the real power comes from combining these features. For example, a generator expression inside a function argument, a decorator that accepts its own arguments, or a context manager for managing database transactions. The more you use them, the more natural they feel.

Pythonic Techniques:

  • Comprehension — concise list/dict/set creation
  • Generator — lazy evaluation for large data
  • Decorator — modify a function without changing its code
  • Context Manager — automatic resource management
  • Unpacking — unpack tuples/lists into variables
  • Enum — tidy enumeration of constants

Code Example

# 1. Generator
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

print(list(fibonacci(8)))
# [0, 1, 1, 2, 3, 5, 8, 13]

# 2. Decorator
def timer(func):
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        print(f"Time: {time.time()-start:.4f}s")
        return result
    return wrapper

@timer
def compute(n):
    return sum(range(n))

compute(1000000)

# 3. Unpacking & Enum
first, *middle, last = [1, 2, 3, 4, 5]
print(middle)  # [2, 3, 4]

Code Explanation

fibonacci generator: The function uses yield instead of return, so it returns an iterator that produces values one by one when looped. a, b = 0, 1 is tuple unpacking at the same time. for _ in range(n) — the underscore _ is used for a variable that is not used. list(fibonacci(8)) consumes the generator into a list.

timer decorator: timer accepts a function func, defines wrapper inside it, then returns wrapper. When @timer is placed above compute, Python automatically replaces compute with timer(compute) — i.e., wrapper. Every call to compute() actually runs wrapper(), which records the execution time.

Unpacking: first, *middle, last = [1, 2, 3, 4, 5] captures the first element in first, the last element in last, and the rest (2, 3, 4) as a list in middle. The * operator can be used in various contexts — including combining lists: [*a, *b].

Everyday Example

Generators are used when reading a 10GB log file — just for line in open("log.txt"): which processes line by line without loading the whole file into RAM. Decorators are used to add logging, caching, or access validation to functions in web frameworks like Flask or Django — just one line @login_required above the view function. Context Managers (with open(...)) close files automatically even if an error occurs — no manual try/finally needed.

At an e-commerce startup, the @retry(max_attempts=3) decorator is placed on the payment API call function — if it fails due to a timeout, it automatically retries up to 3 times. This makes the code cleaner than scattering retry logic in every function.

Summary

Mastering Pythonic techniques such as generators, decorators, comprehensions, unpacking, and context managers separates an average Python programmer from a skilled one. The code becomes shorter, clearer, and has fewer errors. Keep practicing by reading the source code of famous libraries (Flask, Requests, Click) — they are real examples of elegant and efficient Pythonic code.