- Podcasts
- Talk Python To Me
- #404: Clean Code in Python
About this episodeSee the full show notes for this episode on the website at talkpython.fm/404
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
#404: Clean Code in Python
Clean code is one of those aspects of your programming career that's easy to put on the back burner, sometimes more by management than yourself. But it's important in the short term for writing more debuggable and readable code. And it's important in the long run for avoiding having your program take on the dreaded legacy code moniker.
Welcome to Talk Python To Me, a weekly podcast on Python. This is your host, Michael Kennedy. Follow me on Mastodon, where I'm @mkennedy, and follow the podcast using @talkpython, both on fosstodon.org. Be careful with impersonating accounts on other instances. There are many. Keep up with the show and listen to over seven years of past episodes at talkpython.fm.
We've started streaming most of our episodes live on YouTube. Subscribe to our YouTube channel over at talkpython.fm/youtube to get notified about upcoming shows and be part of that episode. This episode of Talk Python is brought to you by Taipy. They're here to take on the challenge of rapidly transforming a Bayer algorithm in Python into a full-fledged decision support system.
Check them out at talkpython.fm/taipy, T-A-I-P-Y. And it's also brought to you by my friends over at Brilliant. Stay on top of technology and raise your value to employers, or just learn something fun in STEM at Brilliant.org. Visit talkpython.fm/brilliant to get 20% off an annual premium subscription.
Bob, welcome back to Talk Python To Me. Thanks for having me back. I'm excited to be here. Yeah, it's really great to have you back. You've been on a couple of times. We started, I believe, our first discussion on the show way back when was around 100 days of code. We went on quite the 100 days of code journey, writing a couple of really, really long courses that were well-received, but it took a long, you know, like nine months for us to write, which was amazing.
And we're back together. It's great to catch up. Yeah, indeed. Yeah, that goes way back to 100 days of Python and two courses that came from it. And I think we also did a Django episode. Yeah. That's right. We did do a Django episode as well. Good stuff. So this time we're back to talk about code quality, writing clean code.
It's in my everyday work. And I think there's a lot to gain from it. So, yeah. Excited to share today. I am too. It's something I really, really care a lot about. It's one of those topics that I think is long lived, which is rare in software development. It's not the latest JavaScript framework or something that's going to last for a year or two.
These ideas are the kind of ideas that just no matter what you're doing, even if you don't do Python, if you do something else, it's very likely that these are solid foundations. Some of the ideas will be specifically for Python, but many of them not. Yeah. Timeless stuff. Yeah. Those are the good ones that are worth putting your time into learning.
Now, before we jump into that topic, which is going to be good, maybe just tell people what you're up to. These days, so I left Oracle a while back. I think we spoke about that in 2020. So, I've been working on PyBytes full-time for almost three years. Congratulations. I know you and I spoke about this beforehand, and it was really a big step for you.
It was. And something you were absolutely looking forward to. But just walking away from a good-paying job, that's scary. Stuff. So, congratulations. Yeah, thanks. This is also around the time that, as PyBytes, we pivoted to doing coaching. So, helping people one-on-one. We created our PyBites Developer Mindset Program.
It's a coaching program. And that really took off. And we have worked now with 100-plus people. But I'm super excited about every day when I wake up. Because helping people overcoming the tutorial paralysis, embracing imposter syndrome, helping them shipping to projects end-to-end is just the best thing ever.
Yeah. To see people grow and become more confident and get better. And, yeah, it's really excellent work, isn't it? Yeah, it's really fulfilling. Yeah. So, congratulations. It's awesome to hear that you're doing that now. And you can put all of your energy, not just your side hustle energy, into these types of things, which I can tell you feels real good.
How about that? Nice. So, yeah, I think that's going to be a theme here. Let's go ahead and jump into it. I reached out to you and said, hey, let's get together and talk about this. Because I knew that you were passionate about these things. But then you also put together a blog post here called Tips for Clean Code in Python.
And I thought, okay, that's interesting. Let me start flipping through here. And there's just a bunch of nice ideas that, you know, resonate with me. So, what I thought we could do is maybe you could set the stage. Like, what the heck is Clean Code? Toon Army did do a pretty good job of kind of giving us the colloquial term.
But, you know, maybe something a little more saphoric and formal we could go with. Set the stage for what is Clean Code? Why does it matter? And then we could dive into some of the stuff you put into your article. And then also, you and I both threw some ideas in after, like, kind of expanded as well.
Yeah, you don't want it. The fewer, the better. Although, maybe you'll leave in one or two in just for a good war story at a conference five years from now. But you don't want too many of those. And I was a free. Yeah. I think it's appreciating the fact that if you do a good job, what you're building will live a long time.
That's great. Ship it. Like, whoa, whoa, whoa, whoa. Ship it. No, no. I just threw it together. It's good. Let's go. Like, we're in a hurry, you know? And then that just starts to build and layer on, like, a sediment that just makes it harder and less fun to work with. And so as you just think about this thing is small now, but as it grows, what are both the practices and maybe technological programming things to bring and put in place so that as it grows, you don't start to just really come to a screeching halt to make changes.
Tests start to fail randomly as you just touch it in various places. Things like that, right? Yeah. It was also kind of my introduction to Python in 2012, so almost 11 years ago when I made this automation framework at work. And I was a big fan of Perl back then. I guess that goes back to my Unix shell scripting initial programming exploration.
And maybe that says a lot about Python as well, that it does inherently things well. Because if you type import this in the REPL and you get the send of Python, a lot of these statements sound so simple, but they're actually so profound. And they actually tell you a lot about writing clean code, in a sense.
So anyway, but I digress. They do. They also talk a lot about the community that cares enough that, you know, you have these sorts of commands in the language itself that remind you to think about writing clean code. And going way back to the late 80s, Gito, when he came up with it, really broke with tradition to use white space for the code structure.
And you've got things like black. And, you know, if you had curly braces, like it could still be quickly put into a pretty shape now. But in the early days, that was a really important concept of it. These days were spoiled, right? Having black out of formatting and all that. When we started, that was not the case.
And at the time, this is long ago, I was doing C#, which is an okay language. It's pretty good. But it has all the symbols and formulas and all the angle brackets and all the stuff that you would do, right? It's not quite C++, but it's pretty close. And when I came to Python, I was like, gosh, it's just weird that a lot of that stuff's not here.
So it's not the first content piece. But I think this one kind of summarizes in a bit more of a concise way. And of course, there's way much more to it. But I think the 10 points here get you pretty far. So those are pretty important. They sure are. So let's start with one that you already kind of laid this out.
Like so many of these techniques, they are like, they sound so simple. And I guess, sure. Obviously, Michael, I wouldn't write a 1000 line function. And you're like, but it's already 700. How did this happen? Right? How do we get here? And the first one solidly falls into that realm, which is smaller units, smaller functions, smaller classes, smaller modules, single responsibility principle, all that, right?
Tell us about this. Yeah, so indeed, a function or a unit of code should ideally do one thing. And just a side note, right? That's usually not how we start. Sometimes I do want to make this side note that when we're figuring out a design, it can definitely happen that you have very large units because you're basically trying to figure out what you're building, right?
And that's where refactoring comes in. But we'll talk about that a bit later. But yeah, I give a very simple example in this article, right? Where a function parses a CSV file, builds up a result list and also prints it out, right? So now this function is doing three things and it probably works and it's fine, but you cannot really easily reuse something that's doing three things, right?
So if you want to plug in this function now into something else, there's a lot of things happening that probably doesn't make it a candidate to reuse in its current shape or form. It's also harder to test because now you have to test parsing and printing. And this is kind of a silly example, but just think about another thing you have in your code that's doing multiple things.
It will just be harder to test because there's a lot more going on. And yeah, as you said, right? These things sound very intuitive and easy to grasp. Yet when we look at code bases, right? This happens all the time. And yeah, so if something's harder to test, it's harder to guarantee that it works.
TypePy core provides intelligent pipeline management, data caching, and scenario and cycle management facilities. That's it. You'll have transformed a bare algorithm into a full-fledged decision support system for end users. TypePy is pure Python and open source. And you install it with a simple pip install TypePy.
The link's in your show notes. Thank you to TypePy for sponsoring the show. And it's write functions that are 10 lines long, not 100 lines long. Now, I'd like to hear your thoughts on this, but my feeling about all of this stuff is, as a general rule, this is what you should do. There will be situations where you might, you know, this is just, I can't think of something better.
I just, I wish it wasn't like this, but it's just weirdly unique. And, but there's, you know, 19,000 other lines of code that are all three lines, five lines type of thing. Right? So it's, for me, at least, this isn't a 100% or you're doing it wrong. It's a 98% or 95% of the time you should be doing this.
There may be some weird case. And I don't know. What do you, how do you feel about that in general on these topics? Yeah, as I said before, sometimes you just don't get the design right from the start. So inevitably you're going to write some longer classes or functions. But then when you break them out in smaller units, the other thing I have to say about that is it gives you an opportunity to better documents.
Because in this example, if you break this long function that's doing three things out into three separate functions, parse CSV, buildup list, bad name, but you get the point, and print results, then all of a sudden we have three units now and every unit has a name. Hence, when you go back after a year and look at that code, which always happens and you always wonder, what the heck was I thinking?
Now you add a glance just by looking at the function numbers, you have just already a better idea. These functions, you can give doc strings as well. So at a glance, you have just a much easier time figuring out what this was about. Yeah, I appreciate you actually gave a shout out to me in this first piece here, which I didn't expect.
Yeah, that's a funny name, right? Code smell. It is. Code that is smelling and this analogy I came up with. But yeah, basically it's code that's not following these best practices and it's just not maintainable, not easy to extend, going back to these principles we mentioned. So yeah, not following these guidelines.
That code can be smelly. It can be as code smell. Yeah. Yeah. Well, the idea is like, it's not actually not working. It's just not nice. You know, you kind of turn your nose up at it when you see it, but it's, you can't say it's broken because it is working. It's a good point. It smells a little bit off, right?
It's not quite broken code, but it's sour. I don't know. And so the reason I bring this up is one of my rules of thumb here that I love, and I think you're kind of hinting that with this little shout out that you gave me in this article is when we come across these code smells often, especially when you're earlier in your career, often the reaction or the first thought is, you know, this part is not nice.
This part is complicated. This part is hard to maintain or hard to understand. So I need to put a nice comment. I've been told, comment your code. Don't be a jerk. Comment it. So I'm going to put a big comment that describes why it's really bad and all that. And in the code smells sort of world, these code comments can be seen as deodorant for the smell.
Like it doesn't remove the smell, but it kind of obscures. Like it's not as bad if you saw the comment saying why the code that follows is bad, but maybe you could just make it not need a comment. And a lot of times, like you just said, that's, well, these five lines of code need an explanation because they're mixed in with all this.
But mostly in their literature, I'm reading that commands are actually not that good. And sometimes even labeled as a code smell in the sense that your code should be kind of intuitive. I think it's going back to that, like half of the time when people are actually putting those comments, it's because there's something kind of messy and they're trying to help you get over that mess or deal with that mess rather than just fixing the mess, you know?
They can read the code obviously, but why you took that decision, what the, and there might just be some extra context that you need to give. Yeah. And it's also different than doc strings potentially, right? Which is kind of a form of a comment, but it's meant to talk about the API and not cover up some weird thing you had to do in the middle.
You know, so it's even our robot overlords are going to, going to help us by taking these comments and removing them, putting the functions there. Help us not replace us, right? Yeah. Hopefully. Fingers crossed. Another thing related to this, strongly related to this, because the more things you have that are smaller units, you're probably still going to have about the same amount of codes.
You have more functions, more classes, more modules, files, and so on. What gets tricky can be naming them, right? So choosing good names also, I think, probably is a message in here that people need to think about. What are your thoughts on that? Yeah, it's funny. Again, another thing that sounds very intuitive, but wasn't there a saying like there are two or three complex problems in science.
One other one I'm going to remember and naming things. Yeah. There's two problems that are hard in computer science. Naming things, cache and validation, and off by one errors. Thank you. Yeah. So naming is up there, right? It is. That's right. I think it goes back again to knowing your design and what you're building.
So it's very easy to then replace that 365 integer with a number on the score of days in a year or something like that. Something that expresses meaning. Yeah. And again, this is kind of an obvious example. But if you have some magic five or six or 87 in there, the reader of this code probably doesn't know what that means.
Right. So if you have a constant uppercase with underscores as per PEP 8 defined at the top of your module, I usually put them in the top of the module. And then in the code, you see like max underscore, blah, blah, blah, a real name. And then immediately makes sense. Right. And it's also a nice way of grouping those variables in one place.
I said top of the module. But if you have many, you could also have a constants.py in your package to group them. You can also use enums to group various constants together if they logically pertain to the same group. And again, all more readable. Yeah. Enums are a great recommendation because instead of saying, well, the default Sunday, so we're just going to put Sunday here.
Now that means nothing to Python. It means nothing. But it means something to type checkers, right? So if you have like mypy or something and somebody tries to change the value of it later, it's going to come at least as a linting type of error, if not a full on runtime error. So this is something people could leverage to go a little bit further.
That's super nice type hinting. As you will paraphrase, it's meaningless to Python. But if you now run your checker and it's somewhere in your code that you try to overwrite that variable, which is perfectly fine, right? Because Python doesn't enforce, doesn't say anything if you now would assign a new value to max size.
Like in this case, a number, it still needs to be an int. Well, what integer are you going to put there? Hmm. Zero. Well, zero valid value. Do you want it to be falsy? Like there's all, could it be negative? Which negative values? And then you see weird tests. Like if it's less than zero, you're like, why is it testing that?
Well, that means it's not set. Like, okay, that's weird. So another idea that I think comes in that's pretty interesting is the sentinel pattern where you come up with a particular number and sort of store that and say this number or value, something you say, if it is this, that means it's unset or it's just a weird case or it's, it's kind of like setting it to none.
But if that's not going to be a case you can use, sometimes none is, is that thing. Right. But not always. Are you familiar with this? Do you do anything like this? I have not really used it. So I had to read a read up on it. I think I use none quite a bit, but I think the, I mean, that's at least better maybe than minus one is the find example at the top.
Yeah. But I think this even wins by being more explicit even, right? By having an object then to test against. Yeah. So one example of a standard library is the config parser has a underscore unset as a global variable and that's its, its sentinel value. BZ2 has the underscore sentinel to just call out the pattern directly there and so on.
My favorite one out of this actually is a variation is this, this null object pattern. So null, because it comes, you know, sort of earlier in the life cycle of languages where null, not none, but where a lot of times if you see if this value is none, then we can do a thing other than otherwise we can do actually work with it.
Right. And you'll see that these, these tests all over. And so this pattern is come up with a sentinel value that is not none, but kind of behaves in a no op way. Right. So you could give it a value of a person who is a sentinel and it just, if you try to get his name, it's just going to return, I don't know, nothing or something like that.
Right. So you can, if it makes sense in that situation, you could remove a lot of these, if thing is none, do something else, do something else just globally, which is really nice. So you don't have to do this non check here. So are you saving an if else? Yeah. You're saving, you're saving the cyclomatic complexity.
So yeah, I do too, because sometimes it's kind of hard to deal with that or you don't control it. A lot of times kind of going back to when I was talking before about the 95% case and I told you about this really gnarly bit of code. that's because I'm consuming two other APIs that I have no control over and they're junky.
They're real junky. So, you know, I've kind of got to like fit it together and, and you don't get a pick whether they use the null object pattern or not. You just got to make it work. Right. Yeah. That's a good point. Yeah. Yeah. Indeed. All right. So those are all kind of under the magic number category, I would say, even though technically some of them are not, like I said, not numbers.
This one, honestly, I'll tell you, you asked me about kind of my first experiences with Python long ago. And this one weirded me out a little bit because it's something I had spent a long time in C, C++, C#, trying to just remove and weed out. And that's global scope. Tell us about this and maybe why to watch out for it.
If we leave something in global scope, for example, we have a global variable and we're pulling that into a function with a global keyword and we're making changes to it. Now this function has side effects, right? So you have the stuff that's going in the function, but it's also mutating some external object, right?
And when you write it, you probably are very aware of it because you're doing it, but you're going back and all of a sudden this might bite you. It will surprise you. Side effects overall are bad, right? And the global scope has that potential because it's global scope. It's not local scope to some class or function.
Yeah. Basically that, that, it can lead to surprises and we don't want surprises in code. Yeah. And it's not an argument you pass to a function. It's not a return value from a function. You might not even know that that is in play as you interact with part of your code, but somewhere out there, it's something deep down is reaching up and seeing that value.
This portion of talk Python to me is brought to you by brilliant.org. You're a curious person who loves to learn about technology. I know because you're listening to my show. That's why you would also be interested in this episode's sponsor, brilliant.org. Brilliant.org is entertaining, engaging, and effective.
If you're like me and feel that binging yet another sitcom series is kind of missing out on life, then how about spending 30 minutes a day getting better at programming or deepening your knowledge and foundations of topics you've always wanted to learn better like chemistry or biology over on brilliant.
Then you're presented with a cool learning path to get you started right where you should be. Personally, I'm going back to some science foundations. I love chemistry and physics, but haven't touched them for 20 years. So I'm looking forward to playing with PV equals NRT, you know, the ideal gas law, and all the other foundations of our world.
With Brilliant, you'll get hands-on on a whole universe of concepts in math, science, computer science, and solve fun problems while growing your critical thinking skills. Of course, you could just visit brilliant.org directly. Its URL is right there in the name, isn't it? But please use our link because you'll get something extra, 20% off an annual premium subscription.
So sign up today at talkpython.fm/brilliant and start a seven-day free trial. That's talkpython.fm/brilliant. The link is in your podcast player show notes. Thank you to brilliant.org for supporting the show. You know, one of the areas where this comes back, where I think maybe things might have been different if the people were able to see the future 30 years in advance, which I'm not expecting they should be able to, would be the global interpreter lock itself with its global description right there.
It's first G, you know? You know, Eric Snow did a lot of work to try to create a per sub-interpreter lock. So it's still a global lock, but global for that sub-interpreter and try to share those within processes. And I recall I talked about just reworking hundreds or thousands of global variables so that they were no longer globally shared, but were more local.
And it's this kind of stuff that can grow and really makes it hard to go forward and make changes. Yeah. Interesting. I think you have had an episode on the GIL and then the refactoring, right? Yes. A couple. I have not had Sam Gross on for his, his like true GIL-less Python work, but he's welcome anytime he wants to come.
Is there a way you can pass this down to the thing that needs it and not just make it global and shared and right. So minimize what is global, I guess, is one of the things. When I first saw that, well, Python is full of just a bunch of modules and functions and the shared state is going to end up in these global variables.
And that seems really, oh my gosh. But if you look at languages like Java, C#, C++, you end up with a lot of static classes. And just because there's a class namespace between your global variable and not, they're the same thing. Right. And so modules and module level variables are very, there's something that you don't want to have too many of, but they're not as out of whack with the rest of programming as I think maybe people might initially see them are.
Right. There's no real difference between a static class and a function and a global variable and a module. Because there's scope to that module. Right. So unless you bring in that module, you don't have access to it. You mean? Yeah, exactly. And if, if you have a class and it has one value and if you have a module as one value, it's really like, it's really semantics on whether they're different.
So I don't feel like putting them in, you know, some languages I'm maybe thinking like, oh, well, we don't have that because we have classes and we put stuff in class. Like if they're static classes, so the same thing. Yeah. Sometimes what confuses people though is, is having a static method or just a plain function outside of the class.
So if you now do a DURL on an instance of that class, that static method shows up, which I found kind of interesting. That is interesting. Yeah. I think there's a lot of places where people think I need a static class or, or something where it could just be a module with functions and maybe a global variable or two.
But if you do have classes and I guess, and you're trying to look what's part of this class, then making that, go ahead and bringing that into the class. That totally makes sense to me. I can see that. I didn't see that presentation, but that makes sense. Yeah. As a form of grouping, but I'm with you with modules and functions.
It can get very far. I would say more people error on trying to build up stuff into a bunch of classes because they've seen that in other languages they're coming from, then they don't quite group it right. You know, like it's, it's more of not idiomatic code, which I guess we're going to get to as well as some of the other stuff.
So linters, tools that automatically fix things. That's what's next. Tell us about this. Yeah. This is really a no brainer in the times we live. And actually, yeah, we're spoiled because there was a time I was just manually fixing stuff like 8 was giving back till the Blackout of 4 Murder came along.
Bob, it was worse. There was a time where we would argue about how it should be fixed. And we, this would be like a conversation. And we'd be like, no, no, no. We put the commas here and we space it like this. It's like, is this really how we should spend our day? And it was time for somebody to step in and give them defaults.
Because I asked the questions. And enter Lukas. Yeah. I asked the question on Twitter the other day, like single or double quotes. And there were like 50 commands. And there's really, yeah, people are really torn about the default style should be. But yeah, Flake 8 to be compliant with Pep 8, which every Python developer should be.
Black for auto-formatting. mypy to the type checks, right? As we said before, Python doesn't enforce it. So you need a tool for that. mypy, hence. Yeah. And then there's also, Flake 8, for example, has a lot of plugins we might go into next. But first I want to highlight, like, you want to automate as much as possible.
And a pre-commit tool is just awesome. It's called pre-commit, right? So it's a tool that runs before you try to make a commit. So it's a great enforcer locally to not commit any code that's not formatted or that has style violations in it. Very easy to use. Very easy to set up. It might take a little bit of work fixing.
I mean, black auto-formatting is automatic, but maybe you need to fix some Flake errors. But I see that as a little bit of work or a little price to pay with every commit to avoid a lot of technical debt over time. One of the challenges I see for a lot of these things, and linters and testing, they're both in this category, is different people on the team who are all working on the same code base have very different levels of commitment to, say, writing or running unit tests or formatting your code so that it all looks nice and clean before they check it in, right?
Like, okay. But we're all in this together. Let's see what... And tools like the pre-commit stuff just mean it's just automatic, right? There's not a person to be blamed for saying, well, why didn't you run it? Or that person makes me run this tool? Or, you know, like there's none of that weird friction.
It's just like the software said, this is what we agreed on and it's not ready. You've got to go, you know, format this line or it'll often just do that itself, right? Yep. What's the saying? If it's not automated, it is broken. Yeah, that's a good saying. This is as simple as putting the YAML in place.
But I think the more you do locally at the individual developer level, the better. You do both. Oh, yeah. So ideally, none of the malformed code gets checked in. And then fixed. And then it shows up as a git diff and, you know, things like that. So you could have it on the server just as a safety net.
I think it doesn't have to be just one try accept block either for one huge function. You know, you could have try accept do some stuff. Try something else if you really need to. You know, you can't disambiguate them by exception type. But also worth pointing out, I suppose, is the accept star stuff, which is not going to be maybe Python.
Oh, that's new. Yeah. Yeah, that's new. And I don't know how to search for it because it seems like the star. Well, whatever. I could just describe. But it's really interesting because you can catch multiple exceptions. And maybe this actually changes the advice a tiny bit. You can catch multiple exceptions for something going wrong.
Not just the last or the first. Right. And with the accept star, you could actually catch all of those errors, say, from like a retry block or something. So. Yeah. Interesting. I don't know. It doesn't make this cleaner or simpler to go with. It only complicates it. But still the idea of like smaller code blocks, I think good advice there.
Yeah. And always name your exceptions. Right. So sometimes I see try except colon. And then we're like, what's exception? Because that will just catch anything. Right. So always be explicit in the exception. I just think you understand how this works. When you put that in there, there's no more errors in the code.
Right. But there's a whole bunch more. And that's your next tip. Yeah. This can, of course, be a whole series of articles because there's so much what can be considered idiomatic or not. But yeah, there's sometimes you see people reinventing the wheel and they can perfectly well use the standard library.
There's also a very rich set of built-ins. Right. Like all any those built-ins. But then also style-wise, there's this concept of leaping, checking before you leap versus just do something and ask for forgiveness rather than permission. So, for example, code that overly checks if a file exists or can be opened.
So all these conditionals. What's often considered more Pythonic is to just try open a file, try to do something and then catch the exception. Right. So that's why it's called. Right. It's easier to ask for forgiveness than permission. Yeah. Yes, exactly. As opposed to like a C language or something where you do six or seven checks to make sure everything is set up just right.
And then, you know, I'm going to check that the file is not just that it's not null and that it has a null terminating character. And now I'm going to check that I have access to the files. You know, you're like there's if you write, if you go and read a lot of C code, there's like check, check, check, check, check, check, check.
Do the thing. And usually that's because there's a page fault and the program just goes, whoof, and just goes away if you touch it wrong. Whereas Python almost always, not always, but almost always the result is here's an exception you can catch and handle. And it tells you what went wrong instead of trying to think of all the checks.
Because there's probably a check you forgot. Just give it a shot. Right? Right. And it's also, it's kind of the positive mindset. Like usually it works. And if it doesn't work, we deal with the consequences. Whereas if you do all these if checks, that's code that always runs and might not be necessary.
So it might even be faster. Right? For sure. So more of the ideas that came to mind when I was reading your idiomatic code section was just one use that you did mention this a little bit, but I'll reinforce it is you said use a standard library. And one of the things I learned from working with you is there, you know, sort of, I would try to pull another, other library, other things from IPI or something.
You're like, look, this is built in. Why don't you just use, you know what? You're right. That's built in. That seems pretty handy. Right? Like, for example, counter is definitely one that I use all the time because of you. And a collection. Yeah, exactly. So embracing what's there instead of maybe getting another library or just trying to write that algorithm yourself because who knew it existed?
Didn't study the standard library enough. I just came from C and this is how we do it in C. So I'm going to try to do that here. Right? Like the idiomatic steps that you can take are really good there. But also lambdas versus regular functions for like little inline things. You mentioned some of the ones that take generators for like all and any and these other tests.
Mm-hmm. Another one that is near and dear to my heart. You're number seven on this list. Near to dear because I have suffered badly the consequences of choosing wrongly is choose the right data structures. Tell us about that. Yeah. This is very important for performance. Right? So where you kind of need to understand just the fundamentals here.
Right? Like list versus sets and dictionaries and how they perform. For example, if you're very big collection of a million items and you would leave that as a list, yet you want to do searches or lookups. Then how this works is they traverse them item by item. Right? Where if you would make that a set, it's now in big O notation, O1, because there's hashing going on.
I mean, obviously, we use dictionaries so much. But if you've got a list, but you think you might need to look up stuff in that list based on, say, if it's a list of objects, some field of that object. If you would make that a dictionary, make the key of the field, then it's not a little bit faster.
I want to build up this list of them. But I want duplicates. You might see if this thing is not, you know, look in the list for it, then you can add it. Like, just don't do that. Just make a set and just jam it in there. And it'll reject the duplicates. Right? Like, there's a lot of things where this ties back to your idiomatic one as well.
Yeah. Another one I highlight there are decks. Right? So when you do inserts and leads on both ends of a sequence, that's also generally slow with a list for the same reason. Because as the search example is that it needs to remap values, right? Massively. And a deck is designed to do that fast on both ends.
It's like, it looks to me like a saw, a lumberjack would use or something. It's just like zip, zip, zip, out, and then back, and then out, and then back. And you're like, whoa. You know, it's usually like it starts in the middle of the editor window and it goes to the right. You're like, what is this?
And, you know, it's usually if some case and then if some other case, maybe do a little step, then if another case. And it's like assuming that it's got to build up a bunch of these steps before it can sort of go down the happy path. So it's going to check everything that could possibly go wrong before it tries to do that.
And I don't know how you feel about guarding clauses. I love guarding clauses. Yeah, you do? So tell people about this sort of alternative. It's so simple, but it makes such a difference. Yeah, it goes back to the Xenophython again. Flat is better than nested. So nested, deeply nested code is just inherently, it's more complex.
Painful. And it's harder to maintain. Yeah, it's called the arrow, arrow shape. I learned from this article that it's also called the staircase, which is nice. But yeah, you can, if you look up our arrow shape, it explains more about it. But yeah, it's just more complex because, yeah, it's again, that cyclomatic complexity, right?
Yeah, I guess, yeah, the cyclomatic complexity, right? The amount of combinations you can have with this is less. Hence, it's less complex. Hence, it's easier to maintain. And readability here is way better. Yeah, I totally agree. So when you see things like flat is better than nested in the Xen of Python, you're like, cool, but I got to test some stuff.
Well, not actually. Like guarding clauses almost always will lessen it, if not really, really decrease it. Yeah, that's a good point. Like the Xen tells you the what, but not necessarily the how. And the guard clause is that this is a particular technique. Another one in refactoring is the extract method refactoring.
And that's where we pull out a bunch of code into a new function, which also often leads to less nested code. Indeed. Is that your next one? Refactoring? Could be. I think that was a bonus. I skipped over a bunch. That's right. It was a bonus here at the end. Absolutely. So that's where you gave a shout out to the refactoring book, which also had those code smells in them.
Yeah, that's a good point. I think the tooling has improved. But still, I think conceptually, this is still an important book. I was reading parts of it again. Honestly, I do like the first edition a bit better sometimes because it uses Java, where this uses JavaScript. And I don't know, the paper quality.
I'm not a fan of Java, but I think I might actually prefer the Java or the JavaScript, to be honest. But it's very fundamental stuff. And, yeah, it still has, it's also nice that it's a catalog, so you don't have to read it end to end. You can just zoom into parts that are relevant for you at that moment.
So, the collection of things. Okay. Very interesting. So, I guess another one, I don't remember if it was directly in your article. I don't think so. It was just sort of implied throughout, was, you know, embrace refactoring. You opened the, alluding to this at the beginning of this conversation, is I see a lot of people who get stuck thinking about, I've got to get this right.
Spend a week on it. If it's not working, it'll refactor to the other. Or even throw it away and go to the other option, right? Like, there's a lot of people kind of stuck. And I think embracing the idea of refactoring, maybe not in the traditional by-hand effect of Martin Fowler's original book, but, you know, we have tools that do a lot of this automatically or almost automatically, you know, right-click and ask it to.
So, what are your thoughts? I definitely think people should at least catch the zen of it, if not go through the book, because the tools will take care of it. Yeah, you still want to know the concepts here. The different techniques, as I already highlighted, the extract method, for example, grouping constants into enums we've mentioned before.
So, a lot of actually what we've spoken about so far can be found in this book as well, right? And I think overall, the goal of refactoring is to keep that technical depth in check, right? So, avoid, suffer a rut, they also say. And, yeah, as you start to add more code and cover more scenarios and the always changing requirements, inevitably, what happens?
You kind of need to learn. You thought it was one thing, but as you got further into it, you're like, you know, that part's actually, that's where the problem is. I didn't think so, but now I know, because that's where it's hard, right? Which you only learn as you go, right? Yeah, that's a good point.
Alvaro says, you could go and put assert statements at the beginning of functions to indicate some of the assumptions that could be disabled in production and give nice errors on pytest. So, pytest, rather. Yeah, possible. What do you think, Bob? Yeah, asserts are great, but, yeah, I'm happy that you highlight the caveat that they can be disabled, so you cannot always rely on them.
I definitely see a place for asserts. And, of course, you use them in pytest all the time to assert different ways your function performs. I use most of my asserts in pytest, yeah. But I can definitely see a place for this scenario that Alvaro highlights. Yeah, and then Brandon Outlawdience has a very realistic problem that people run into is, I work a lot of places where they don't give you the time to do the refactoring and make things better.
And so it just builds up until it becomes not ideal, as his second comment here implies. That's a good point. That is a real problem. And I'll tell you how I solved it. Bob, maybe we're getting short on time, but you can tell me real quick how you solved it. For me, when my managers and folks would say, Michael, what is your estimate for how long this is going to take?
If I thought it was going to take five hours, but maybe I would need to do an hour or two of refactoring, this feature took seven hours. Like, you want it done, it's going to take seven hours. Because if I'm going to do it, I'm going to do it right, because I'm going to have to work on it afterwards.
And I know it's just going to get worse if I... So I wouldn't exactly lie to them, but I would include the time to make it right, not just make it work as part of my estimate. Yeah, maybe even double it, right? Because there's the initial version, and there's the testing, there's the documentation, there are bug fixes, there are inevitably are requirement changes in the sprint meetings.
That's a nice one. Exactly. That is a good one. Very good. All right. Well, we're getting short on time here. Let me do something. I want to do something that's kind of different, Bob, because I think this is actually... Let me share a different thing here. I think that this is something people are going to have to start thinking about as well as maybe an option here.
What else can we do? Is it based in the article as well? No, I didn't give it the article. Just the headings. So it says you can document your code. Keep it simple, which it didn't understand. Follow PEP 8. This is an interesting one. Exceptions are for error handling. So anyway, I just thought it might be kind of fun to think about, you know, could we ask these things to help us and improve our code?
I don't know if you played with any of this, but it could be fun. I have not yet. That's Julian's department. He's geeking out over the tool. But I'm high on my list to try it out because it's really mind-blowing. What this tool is doing. Yeah. I had a program that I wrote. And let's just see if I can go to, let's grab some random gist here on GitHub.
Let's see. So you can take these things, this random code, and say, you know, things like, here's a Python program. How can I make it more readable? You can give it this long thing and it'll say, you know, look, there were no doc strings. There's some places where you had meaningful variables are missing.
We'll see. So anyway, that was fun, but let's, let's close it out. Yeah. Excellent work. I mean, I feel like we only just touched the surface, right? This could go on and on. JF out in the audience asked about unit testing and we barely touched on that. There's a bunch of, bunch more areas, but I think we're out of time.
Yeah. The sun is coming up in your world. I can see. Thousand pager books have been written about this. It's, it's a whole field. So yeah. Yeah. We, we mentioned a couple of important things, I think. Yeah. We sure did. Well, it's certainly a lot of things that people can take and they do sound simple.
Well, quick two final questions before you get out of here. If you're going to write some clean Python code editor, what do you use these days? Well, the coaches, the team almost had me on VS Code, which is an amazing idea. But it was not as super fast, of course, but for me, for my workflow, it was not as fast as Vim.
So I stuck with Vim and I do everything. It's just a setup, right? With all the plugins and shortcuts. And it makes me fast. And the muscle memory. Yeah. Yeah. It's one of those things where, you know, you could change to something potentially, but how long are you going to be in a degraded state of working before you gain enough experience?
That's very cool. Yeah. Yeah. Excellent. All right. Well, thank you for being on the show. Thanks for writing the article. And good to catch up with you as always. Yeah. Thanks for having me. This was so much fun. I'm happy to share. You bet. Bye. Bye, everyone. Bye-bye. This has been another episode of Talk Python To Me.
Thank you to our sponsors. Be sure to check out what they're offering. It really helps support the show. TypeI is here to take on the challenge of rapidly transforming a bare algorithm in Python into a full-fledged decision support system for end users. Get started with TypeI Core and GUI for free at talkpython.fm/typeI.
T-A-I-P-Y. Stay on top of technology and raise your value to employers or just learn something fun in STEM at brilliant.org. Visit talkpython.fm/brilliant to get 20% off an annual premium subscription. Want to level up your Python? We have one of the largest catalogs of Python video courses over at Talk Python.
We should be right at the top. You can also find the iTunes feed at /itunes, the Google Play feed at /play, and the direct RSS feed at /rss on talkpython.fm. We're live streaming most of our recordings these days. If you want to be part of the show and have your comments featured on the air, be sure to subscribe to our YouTube channel at talkpython.fm/youtube.
