
Pybites Podcast
The Pybites Podcast is a podcast about Python Development, Career and Mindset skills.
Hosted by the Co-Founders, Bob Belderbos and Julian Sequeira, this podcast is for anyone interested in Python and looking for tips, tricks and concepts related to Career + Mindset.
For more information on Pybites, visit us at https://pybit.es and connect with us on LinkedIn:
Julian: https://www.linkedin.com/in/juliansequeira/
Bob: https://www.linkedin.com/in/bbelderbos/
Pybites Podcast
#059 - 10 Python clean code tips drawn from code reviews
This podcast episode is based on this article.
Additional resources:
- 10 Tips to Write Better Functions in Python
- Linting tools: flake8, black and pre-commit on which we have a training: Increase Python code quality with pre-commit
- Mentioned Vim plugin I use to disallow save if there are syntax errors
- Two exception handling articles: 7 Tips to Improve Your Error Handling in Python and Errors should never pass silently
- Not mentioned but relevant for the namespaces part: When to Write Classes in Python And Why it Matters
- Useful Python Built-in Functions [Beginner / Intermediate]
- Idiomatic Python: EAFP versus LBYL
- Zen of Python (or type "import this" in the REPL) / PEP8
- A great book in this context is Uncle Bob's Clean Code.
---
Thanks for listening. If you struggle with this, check out our PDM coaching program where we can significantly increase your Python and developer skills in 10 weeks.
Long sequences of if elif, elif, Elif Elif else that gets pretty ugly and unmaintainable. You can actually use a dictionary or mapping to have a set of conditions as your keys and a set of things you want to do as your values. And the mapping is way cleaner and easier to extend. Hello, and welcome to the Py Bytes podcast, where we talk about Python career and mindset. We're your hosts. I'm Julian Sequeira. And I am Bob Beldebus. If you're looking to improve your python, your career, and learn the mindset for success, this is the podcast for you. Let's get started. Welcome back to the Pyrites podcast. And today it's just me, Bob, and what I'm going to talk about is ten things we picked up from code reviewing. Well, we picked up many more things, but I just made a selection of some common things I'm highlighting in code reviews. And look at the podcast description as well, because I will provide some useful pibytes article references that can really help you improve your python code, but even your programming skills overall. Here we go. One, break long functions or methods into smaller ones. So, as per the single responsibility principle, a function or class or any unit should do one thing. So once you start noticing that your functions are doing multiple things, it's time to refactor and break those out in multiple functions. It sounds very obvious, but I do see it a lot in code reviews that functions are just doing too many things and then they're harder to test and they're harder to isolate, harder to reuse. A few weeks ago I wrote an article about writing better functions, and this was part of it. Two, move magic numbers that are sprinkled in your code to constants at the top of your module. So I often see in code reviews 610 used in a range, for example, or there's a magic 55. So they're called magic numbers because we don't know really what 55 means. If it's just mentioned somewhere in a function, it's very easy to just give that a name, right? So max allowed retries. Maybe if you have a three somewhere sprinkled in your code, way more readable. If you give that a name, you can also move such a random number up into your function parameters, and then the function becomes more robust because now you can call it with different values. Three, watch out for anything that you put in a global scope. Localize variables as much as possible and you'll have less unexpected side consequences. And as the Zen of Python says, namespaces are one honking great or dear? Let's do more of those. And it's true that if you, for example, have a variable in your module scope, and you start to access that in your function using the global keyword that's asking for problems, because now your function can change that variable in the outer scope, which is causing side effects. And this goes back to a function doing one thing, because if a function is going to change a variable that's outside of its scope, then we're having side effects and it leads to hard to trace bugs. So yes, be wary of the scopes and for example, use classes to have a closed namespace and better control what gets accessed. And the same goes for functions, right? You can make variables localized by passing them in as arguments, instead of referring to outer scope variables by using the global. So if you see global, it might be time for a class or refactor it in another way. Four, use flakate or black out of formatting. This goes back to the sooner we catch bugs, the better. And setting up your environment to do linting goes a long way. I also have a vim plugin I will link below that. When I hit save, it will warn me about syntax errors. And this goes all back like the sooner you can catch bugs. So in your ide or environment, the better, the more efficient you become. As a developer and I use for some projects black with pre commit, so it automatically runs before committing. But I also still run flake eight manually, but black will save you a lot of time. Five, keep try, accept blocks narrow. One of the main things I highlight in code reviews, if there's a lot of code like 2030 lines between a try and accept. And that usually means that we should reduce the amount of code that's between the try and accept. Because what is the try and except really trying to catch? It's no way that all those 20 lines are going to raise that exception. So if you see a big block between try and accept, try to narrow down and ask yourself which lines are actually going to raise those two exceptions. And then also avoid the bare exception where you just do accept colon. Always make your exceptions explicit. And we have a whole article about exception handling, how to improve it, and I will link that below. Next up is number six, leverage the Python language pythonic code. It sounds obvious, but there are sometimes things I see that can be more idiomatic. For example, when you do a try, finally, the finally really is to guaranteed close something off, right? Even if it's try or accept. Either way, always run the finally clause and you can actually do that with a width statement. So that's an example where a wit statement is more appropriate. Another style thing is to ask for forgiveness instead of permission. So overly checking if a file exists, or overly checking if something is in the dictionary, you can use a try and accept and assume that something is going to work and deal with the exception in case there's an exception. And that's commonly referred to as ask for forgiveness. And there's a great article by Brett Cannon idiomatic Python EAFP versus lbyl and I will link that below. A last example here is to rely on Python's concept of truthiness. If, for example, my list can have zero more items, you don't have to do like length of my list greater than zero, you can just do if my list. And if the list has more than zero items, then that means truthy and an empty list is falsey. So you can just rely on Python's truthiness concept seven use the right data structure here. One I want to highlight is sets versus lists. So lists are great. Use them everywhere. But when you want to check membership sets and digs, use a hash table so they have zero one performance. They're very fast to look things up. So if you want to look for membership using the in operator, then sets and digs are very performant and those are kind of nuances that go a long way if you're writing efficient code. So use the right data structure closely related to that number eight leverage the standard library. Often in code reviews I see attempts at reinventing the wheel, but there are so many modules and functions and classes in the Stanley library that saves you a lot of work. For example, collections counter is, well, does what it says, it counts things and you have a most common method on it, one line of code, often with a lot of behavior. You can use built ins like sum all, any max min sorted, and they all do their thing in very little code. So yeah, if you're relatively new to python then it's worth to take a look at the Python built ins and we have a YouTube video on it I will link below. Another example is the itertools module. Excellent module of functional code. You have count, you have permutations, combinations, cycle functions that can do powerful things in very little code. Nine long sequences of if elif, elif, elif elif else that gets pretty ugly and unmaintainable. You can actually use a dictionary or mapping to have a set of conditions as your keys and a set of things you want to do as your values and a mapping is way cleaner and easier to extend. Lastly, number ten and I could highlight many more, but we're going to stick to the time and only do ten. This time flat is better than nested from the Zen of python. And yeah, one last common thing I highlight in code reviews is when code gets very nested and that again goes back to functions doing more than one thing, the level of nesting goes up. So see if you can break it down in multiple functions, see if you can return early from a function. All these things that can reduce the amount of nesting or indenting and that makes usually for better maintainable, easier to test, easier to reuse code. So hope that helps. Hope you go back to your code and apply some of these tips. Although there have been an audio, I hope this is kind of an experience for a podcast to talk code on audio, but so many mindset and julian not being here, I took the liberty to do a little coding episode. Hope you liked it. Next week we will be back together. Or actually I think we have an interesting guest. Either way, thanks for listening. Thanks for all the nice feedback and we will be back next week. We hope you enjoyed this episode. To hear more from us, go to Pibyte friends, that is Pibit es friends and receive a free gift just for being a friend of the show. And to join our thriving slack community of python programmers, go to pybytes slash community. That's pibit es community. We hope to see you there and catch you in the next episode.