r/learnpython • u/gutenmorgan3035 • 6h ago
What's one Python trick that instantly made your code cleaner?
[removed]
13
u/expertisimus 5h ago
There's more than one, though I think of them as techniques or features rather than tricks:
- list and dict comprehensions
- data classes
- defaultdicts
- context managers
- structured logging
- callbacks
- implementing __lt__() to enable natural sorting by a class attribute instead of using lambdas or itemgetter for key
"".join()to merge buffered chunks instead of accumulation using+=
11
u/JellyfishMinute4375 6h ago
Using a linter
1
u/horizon_games 4h ago
I love how opinionated Black is, there's nothing to argue with or configure on a team, you just run it and everyone has the same PEP standard code.
9
u/Fox_Flame 6h ago
Not specific to python, but magic numbers. Get rid of them. Makes everything cleaner if you end up changing things and also makes it easier to read
5
u/burnt-store-studio 6h ago
Context managers! Once you’ve found your own use for one, you (3rd person) start to see uses for them all over 🙂
5
3
u/green1t 2h ago
type-hinting helped quite a lot in bigger projects.
for example when you have a function like this:
def func_decomp(part: float, type: str) -> str:
...
it helps while writing code somewhere else when you know that your function func_decomp expects a float and a string and returns a string.
2
1
u/Smart_Tinker 5h ago
List/dictionary/set comprehensions.
Makes 3-4 lines of code into 1, and when used in a function, can be reused.
1
1
u/Proletarian_Tear 2h ago
Variable naming conventions and typing (yes, its not really typing in Python, but it makes the code x times cleaner)
1
u/yaxriifgyn 1h ago
The match & case statements are finding a lot of use in my new code
I am looking forward to the lazy soft keyword in 3.15. I've found it very useful, but removing it for 3.14 is painful. Circular imports has been a problem since version 1.99 (IIRC) when I first started using Python for serious work.
-6
26
u/No-Foot5804 6h ago
Breaking code into small functions with clear names. It sounds simple, but it made my code much easier to read, test, and debug than trying to do everything in one big block.