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)
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"}
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
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"
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
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
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
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)