Five simple tips to make your Python code more readable and optimized
Is my code good enough? It works, but can it be more optimized? Can I shorten it a bit? Is it readable? Well - we all ask these kinds of questions at all stages of our developer careers. I will share some easy tips with you on how you can improve your code style in Python.
1. Use exit conditions
> What are exit conditions?
Good question :) Exit conditions are the ones that we make use of when we DON'T want something to happen. They are very handy in order to keep our code simple rather than nesting it with unnecessary indentations.
Imagine that you have to check if the number inside of a list is even and then check if it is smaller than 10 - if it is then check if it is number 2.
Now you might be thinking - hey I can do this huge condition and put it all together - and you are right, but this is a simple example, imagine if you had five more conditions along with the ones I gave. Your code readability would drop significantly :)
Instead, we can make use of exit conditions.
lst: list[int] = [1, 4, 6, 8, 2, 10]
for el in lst:
if el % 2 != 0:
continue
if el > 10:
continue
if el != 2:
continue
print("2")
We continued the loop if any of the given conditions were not met. Once we get to the print
statement, we know for a fact that every other condition was met and that our number is actually number 2. No code nesting occurred :)
2. Function returns
Similar to the above, this one is also related to the unnecessary code nesting.
Let's say that your function has to return "even" if the number is even and "odd" if it is not even. What some people would do is something like this:
def check_number(number: int) -> str:
if number % 2 == 0:
return "even"
else:
return "odd"
While this will work, we can do a little tweak to optimize it:
def check_number(number: int) -> str:
if number % 2 == 0:
return "even"
return "odd"
Notice how we can make use of the return
statement to match any other condition than one that we put next to the if
statement. So if the given number is not even, we automatically return "odd".
BONUS - we can also do a one-liner but it might mess up readability:
def check_number(number: int) -> str:
return "even" if number % 2 == 0 else "odd"
3. Type hinting
You may have noticed that in the above examples I used type hints. For example number: int
. We know for a fact that Python is a dynamically typed language which means that we DON'T have to specify the variable type upon declaration and that variable type can change during the code execution. What was once an integer could become a list and so on.
> Why would I do it then?
To make everyone's life easier. Whoever picks up on where you left your code will not have to do a complete trace of the function calls or variable names in order to find what type that variable actually is (list, string, integer, ...). Also, type hinting activates the autocomplete inside of your favorite IDE so it is way easier to develop for you too.
4. Use a tuple instead of a list
If you come across a situation where you know how many elements you have to store, and you won't need to change them - perhaps you should use tuples
instead of lists
.
Tuples store the exact number of elements and they can't be changed - which means smaller size. Lists, on the other hand, can be extended
or appended
which means they will allocate much more space than what is actually needed.
Speed is also a key component here :)
Take a look at the benchmark below:
import timeit
lst_code: str = "[1,2,3]"
tup_code: str = "(1,2,3)"
t1: float = timeit.timeit(lst_code, number=10000)
t2: float = timeit.timeit(tup_code, number=10000)
print(f"{t1:.20f}")
print(f"{t2:.20f}")
My output is:
0.00023555899997518281
0.00004893300001640455
Huge difference in speed eh?
Keep in mind that this is a simple example and your production code might show different results.
5. Context managers
Recently I wrote about context managers, so in order not to repeat myself on all the benefits and examples of when/how/why to use them, please click here to read more.
6. Conclusion
I hope that some of these tips will be useful to you in your professional career advancement. Keep your code as clean as possible and as readable as you can. While code formatters and code linters can help to format your code, only you can make it readable and simple to understand.
Like always, thanks for reading :)