9 Advanced Python Tricks That Will Make You Look Like a Pro

If you want to write cleaner, faster, and more Pythonic code, these 9 tricks are a must-know.

9 Advanced Python Tricks That Will Make You Look Like a Pro
Photo by Manny Moreno on Unsplash

These aren’t party tricks — they’re power tools hiding in plain sight.

9 Advanced Python Tricks That Will Make You Look Like a Pro

Python’s elegance isn’t just about clean syntax — it’s also packed with advanced capabilities that, when used correctly, can make your code more powerful, flexible, and expressive.

Whether you’re writing libraries, APIs, or data pipelines, these 9 advanced Python tricks will help you level up and write smarter, not harder.


1. Use functools.lru_cache to Instantly Speed Up Expensive Functions

Memoization can boost performance dramatically, and Python gives it to you out of the box:

from functools import lru_cache 
 
@lru_cache(maxsize=128) 
def fib(n): 
    if n < 2: 
        return n 
    return fib(n-1) + fib(n-2)

No need to manually track previous calls — Python handles it for you.

Great for recursive algorithms or API calls that return predictable results.

2. Use Walrus Operator (:=) for In-Expression Assignment

Python 3.8 introduced the “walrus operator” — perfect for reducing repetition:

while (line := file.readline()) != "": 
    process(line)

Before:

line = file.readline() 
while line != "": 
    process(line) 
    line = file.readline()

Cleaner, and often more performant.


3. Unpacking Dictionaries in Function Arguments

Sometimes a dict is all you have — Python lets you unpack it directly into function arguments:

def greet(name, age): 
    print(f"Hello {name}, you're {age} years old!") 
 
person = {'name': 'Aashish', 'age': 25} 
greet(**person)

You can even combine args and kwargs like a wizard:

def add(a, b, *args, **kwargs): 
    ...

4. Context Managers Beyond Files

You already know this:

with open('file.txt') as f: 
    data = f.read()

But you can create your own custom context managers using contextlib:

from contextlib import contextmanager 
 
@contextmanager 
def debug_block(title): 
    print(f"--- Entering: {title} ---") 
    yield 
    print(f"--- Exiting: {title} ---") 
 
with debug_block("Data Processing"): 
    process_data()

Perfect for logging, managing resources, or wrapping setup/teardown logic.


5. Dynamically Import Modules with __import__()

Need to import a module from a string name (e.g., user input)?

module_name = "math" 
math_module = __import__(module_name) 
print(math_module.sqrt(16))  # 4.0

This trick is useful for plugins, CLI tools, or modular frameworks.


6. Use setattr() and getattr() for Dynamic Attribute Access

class Config: 
    pass 
 
config = Config() 
setattr(config, 'debug', True) 
print(getattr(config, 'debug'))  # True

Ideal for frameworks, metaprogramming, and dynamic object creation.


7. Dictionary Merging with | Operator (Python 3.9+)

Instead of:

merged = {**dict1, **dict2}

You can write:

merged = dict1 | dict2

And for in-place merging:

dict1 |= dict2

Clean, expressive, and made for modern Python.


8. Use dataclasses for Cleaner, Less Verbose Classes

Python 3.7+ introduced dataclasses, and they're a game changer:

from dataclasses import dataclass 
 
@dataclass 
class User: 
    name: str 
    age: int

This automatically adds:

  • __init__
  • __repr__
  • __eq__

Less boilerplate, more productivity.


9. Introspect Functions with inspect

Need to peek under the hood of a function? Use inspect:

import inspect 
 
def sample(a, b=10): 
    return a + b 
 
sig = inspect.signature(sample) 
print(sig)  # (a, b=10)

Or:

print(inspect.getsource(sample))

Invaluable for building debuggers, serializers, and smart CLI tools.


Final Thoughts

Advanced Python isn’t about writing clever code — it’s about writing powerful code that stays clean and maintainable. These tricks are used in real-world libraries, frameworks, and production systems — not just for show.

Master them, and you’re not just coding — you’re crafting.


Which trick was your favorite? Got another Python gem to share? Let me know in the comments!

If you found this helpful, give it a clap and follow for more deep dives into Python and software craftsmanship.

Photo by Fonsi Fernández on Unsplash