The walrus operator :=
can be really helpful, but if you use it in convoluted
ways it will make your code worse instead of better.
Use :=
to flatten a sequence of nested if
s or to reuse partial computations.
In Python, if you are doing something that may throw an error, there are many
cases in which it is better to "apologise than to ask for permission".
This means you should prefer using a try
block to catch the error,
instead of an if
statement to prevent the error.
How should you unpack a list or a tuple into the first element and then the rest? Or into the last element and everything else? Pydon't unpack with slices, prefer starred assignment instead.
The "Zen of Python" is the set of guidelines that show up in your screen if you import this
. If you have never read them before, read them now and again from time to time.
If you are looking to write Pythonic code, write code that abides by the Zen of Python.