DEV Community

郑沛沛
郑沛沛

Posted on

7 Python Tricks That Senior Developers Use Daily

Every Python developer picks up tricks over time. Here are 7 that I use almost every day.

1. Walrus Operator (:=)

Assign and test in one expression:

# Before
data = get_data()
if data:
    process(data)

# After
if data := get_data():
    process(data)
Enter fullscreen mode Exit fullscreen mode

2. Dictionary Merge (|)

Python 3.9+ lets you merge dicts cleanly:

defaults = {"theme": "dark", "lang": "en"}
user_prefs = {"theme": "light"}
config = defaults | user_prefs
# {"theme": "light", "lang": "en"}
Enter fullscreen mode Exit fullscreen mode

3. F-String Debugging

Add = after a variable in f-strings:

x = 42
print(f"{x=}")  # x=42
name = "Alice"
print(f"{name=}, {len(name)=}")  # name='Alice', len(name)=5
Enter fullscreen mode Exit fullscreen mode

4. Structural Pattern Matching

Python 3.10+ match statements:

def handle_command(command):
    match command.split():
        case ["quit"]:
            return "Goodbye!"
        case ["hello", name]:
            return f"Hello, {name}!"
        case _:
            return "Unknown command"
Enter fullscreen mode Exit fullscreen mode

5. itertools.chain for Flat Iteration

from itertools import chain

lists = [[1, 2], [3, 4], [5, 6]]
for item in chain.from_iterable(lists):
    print(item)  # 1, 2, 3, 4, 5, 6
Enter fullscreen mode Exit fullscreen mode

6. contextlib.suppress

Cleaner than try/except for ignoring specific errors:

from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove("temp.txt")
# No crash if file doesn't exist
Enter fullscreen mode Exit fullscreen mode

7. functools.lru_cache

Free memoization:

from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

fibonacci(100)  # Instant, not heat-death-of-universe slow
Enter fullscreen mode Exit fullscreen mode

Key Takeaway

These aren't fancy tricks — they're practical patterns that make your code shorter, cleaner, and more Pythonic. Start using one today and it'll become second nature by next week.

🚀 Level up your AI workflow! Check out my AI Developer Mega Prompt Pack — 80 battle-tested prompts for developers. $9.99

Top comments (0)