Pydon'ts – Write elegant Python code (v1.1)

This video features Rodrigo GirĂŁo SerrĂŁo at DjangoCon US 2021 in Online.

Pydon'ts – Write elegant Python code (v1.1)
0:45:21
Published October 22, 2021
1,263 views

Python's shiny frameworks drive some people to spend too little time learning the basics, which makes it harder in the long run to develop successful applications.
Join me for the hypothetical learning journey of a Pythonista as we refactor a function and learn powerful vanilla Python features.

This talk was presented at: https://2021.djangocon.us/talks/pydon-ts-write-elegant-python-code-v1-1/

LINKS:
Follow Rodrigo Girão Serrão 👇
On Twitter: https://twitter.com/mathsppblog
Website: https://mathspp.com/blog

Follow DjangCon US 👇
https://twitter.com/djangocon

Follow DEFNA 👇
https://twitter.com/defnado
https://www.defna.org/

Video production by the speaker and DjangoCon US 2021 Volunteers.

Summary

Elegant Python code is built through small, deliberate refactorings rather than by rewriting everything at once. Using a function that alternates the case of characters as an example, Rodrigo GirĂŁo SerrĂŁo shows how readable whitespace and names, direct iteration with `enumerate`, limited nesting, and standard-library tools such as `itertools.cycle` and `zip` progressively clarify intent and remove unnecessary structure. He also explains why narrowly scoped `try` and `with` blocks make exception handling safer and release resources sooner, and argues that Django developers should learn core Python and the standard library alongside the framework.

Key takeaways

  • Whitespace, meaningful names, and clear formatting reduce the cognitive load required to understand code.
  • Use direct iteration instead of building indices with `range(len(...))`, and use `enumerate` when both indices and values are needed.
  • Keep `try` and `with` blocks as small as possible to avoid catching unrelated errors and to release resources promptly.
  • Reduce nesting to make dependencies and intent clearer, while also looking for duplicated operations that can be factored out.
  • The standard library, including `itertools.cycle` and `zip`, often provides a direct expression of the problem and can replace verbose control flow.
  • Django knowledge is not a substitute for core Python fundamentals; learning Python incrementally makes it easier to build and refactor application logic.

Summarised automatically from the transcript.

Transcript

7,187 words · auto-generated Show

Automatically transcribed, so expect mistakes in names and technical terms.

0:30

Hello everyone and welcome. My name is Rodrigue Giron Segon, and it's a pleasure to be here with you today at DjangoCon US to tell you all about my talk entitled Python's Write Elegant Python Code. And before we jump straight into the talk, I would like to tell you just a little bit about myself so that you know who's talking to you. And like I said, my name is Rodrigue Giron Son. Right here you have a photograph of me and probably over here you have an overlay of my face so now you get to see two of myself. And I have a or my formal education is in mathematics. I have a master's degree in applied mathematics, and I have been writing Python code for around nine years or probably ten years by the time you watch this

1:16

And the the my main activity or the thing that takes up most of my time is doing some training and teaching of Python and mathematics and related fields of knowledge over at my website at mathspp. com and then I also do some training and teaching of APL for Dialogue Limited. Now, before I actually start with the talk, there's I'll be writing some code and the I will also want to share the talk slides with you later and also the references that I will show by the end of the talk So if you follow me on Twitter at mathsppblog, by the end of the talk I will be publishing all of the resources, all of the links, everything, so it's easy for you to grab everything you don't need to worry

2:03

About jotting things down during the talk, etc. You can just pay attention to what I'm showing you. So, yeah, feel free to feel free to follow me on Twitter. Now Yesterday, well not yesterday, but a couple of days ago, I was browsing Stack Overflow and I found out that there was this person that needed some help to implement A part of their logic or the part of the logic related to a Django app that they were building. And the thing that they needed help with was to generate memes And it they wanted to generate memes like this where they have the SpongeBob picture that is fixed and then the user types in some text And what the Django app does is it takes the text, takes the text, it changes the casing of the letters to

2:53

to to have them alternating like you can see in the picture, it prints the the the text in the picture and then it returns the picture for the user to download or to post on social media or what's or whatever. And what did what they needed help with was They actually knew how to build the Django stuff, but they they didn't know much core Python and so they needed help building the you know the logic that did this casing and so What I did was, well, I thought, you know, I'm I'm really good at Python, so let me let me just write some code, write the solution, and share it with this person. And I was having breakfast at the time, so I had to do this on my cell phone, but you know I'm so good at Python that I thought well I I'm sure I can do this even if I'm on my phone having breakfast, and so I did well.

3:41

Let's do a let's define my function that's going to take some A, and then we start with some empty list, and then what we need to do is we need to go over all of the indices in the range of the length of my text, and then If when the index is divided by two, if the remainder is zero, then what I want to do is I want to append to the empty list. The A of I in uppercase, and otherwise I want to return the A of i in lowercase And by the time I'm done, I just want to return the join of everything so that the list now becomes a string. And I was feeling pretty good about myself and I just thought well let's let's just make sure that the function works as needed.

4:29

So let's type in the the text that was written in the image so Django sucks Flask is better and then when we print we can see that this is the output. And looking for example at the uppercase U and the uppercase B, comparing it with the original image from the task we can see that this is matching so probably we got you know we got the pattern right and I was, you know, I gave myself a pat on the back. I'm I'm so good at this, I just wrote these eight lines of Python code on the first try and they just work. And all of a sudden my my girlfriend walks past me. She she looks at at me over her shoulder and she says, Well, Houdri, what are you doing? I thought that Python was the language where where white space

5:15

mattered. And I was about to tell her, yeah, it does matter because you use white space, you know, in the indentation to to make sure that the the you know the if statements are inside the the force and whatever But then it struck me that's not what she meant. What she meant was that white space really matters, you know, you have to you have to put white space around the operators and around the assignments in order for the code to breathe You know, and even an empty line every now and then actually helps you read your code. And so I just, you know, out of instinct I followed my girlfriend's comments and I changed the function to look like this

6:01

And I noticed that I didn't break the function, so I was feeling pretty good about myself, you know. I'm so good at Python, I just wrote this piece of code that works so well and that really does the task. But I was already done with breakfast, so I had to pack my things and you know grab my phone and my computer and whatever and I left the house or rather my home and I went to the metro or to the subway or whatever you call it. And as I was waiting, um I took my phone out because I needed to submit the you know my answer on Stack Overflow. And as I was about to do that There's this crazy looking person you know with the with the hair all pointy and sitting next to me and they go, well Good morning, I don't know who you are, but I was I was I couldn't help but notice that you have some code over there.

6:49

And you know I'm studying some some psychology and some stuff related to the brain and I really should tell you that, you know, naming matters. And I was I was kind of confused. I'm I'm slightly I'm kind of an introvert, you know, and so it really strikes me when I'm just sitting waiting for something and a random person starts talking to me. But they they didn't really bother with that. They just kept going and they were saying, you know, names really matter because it's like your brain. You feel, you know, we humans have this idea that we are so good and so smart because we ha we are the only we we are the only smart animals in the world and whatever, but actually our brain has very limited power and very limit a very limited capability to hold different things

7:35

um in you know in in your in your Conscious self at the same time. And that's why you need names, you need labels to help you hold all these different things, ideas, thoughts, objects, concepts in your head at the same time And so if you don't use proper variable names, then this all becomes much harder because you don't have proper names to refer to things. And so there's a bigger cognitive load in your brain. So you really you should really Change the names of your variables in your code before you submit to that on Stack Overflow. And I was just looking at that person and I thought, huh? Cause I I was pretty sure I didn't ask them anything, but you know, I just I swallowed my pride

8:21

and I copied the code and I pasted it, which which is something you should always do, right? You should copy and paste your code all over the place. And then I change the name of my function to something like alternate casing, because that's essentially what muff my function is doing. And then, you know, instead of calling this the empty list, which is kind of silly. Because even though this is empty, it will stop being empty very soon. So I just called it Cars As in now let me replace this. I want to replace the empty with cars, you know, short for characters, because I'm lazy. And then instead of A, I thought, well maybe I could call this text. And now let's do magical multi-line typing. And then also another personal favorite of mine, instead of doing i, I like to type in idx, which is short for index.

9:13

And so I took a look at the code now, you know, I changed all of the names, I tested the function again, and I thought, well, damn, I'm really good at this, I'm really good at Python, just take a look at the function I just wrote. And I was about to paste it on Stack Overflow, but then the subway or or the Metro or the tube or whatever arrived. And so I got up and so did the weird person sitting next to me, but I I just went away, you know, because I didn't want to go in the same carriage as that person. And then it's, you know, I live in Lisbon and you probably don't know, but it's it might also be similar to to how it works with you in early in the morning. The metro is always jammed with people. So I kinda had to force my way into the carriage.

10:01

You know, with my phone like this. I was standing like this And as I was typing and pasting my code on Stack Overflow, there's this person, it's well standing really, really close to me, and they go like Hey, hey, no, hey, hey. Haven't you heard of enumerate? And I looked at that person and I was like, what? Huh? What's what's that? And they just tell me, well, there's this cool thing in Python called enumerates, and I can I can type it in here enumerates. I think I was pronouncing that weird. So enumerate and it's a built-in function so clearly this I didn't define this previously

10:47

and this was not an error so this is something that's built in the language And this enumerate function is really cool for you to use in Python and especially when you're doing looping with for loops, because what enumerate does is It allows you to work with the elements of an iterable and their indices at the same time. And to help you understand what that means is if I just create A short list over here with three items, you know, if you come from a C background or something like that, maybe you're just you're too used you might be You know, inclined to type something like this. So there's this I variable that's going to represent all of the indices of the list, and then you use the range of the length of my list

11:35

to build all of those indices And then you you do something with the elements by indexing, you know, something like that. But this is very redundant because you started with a list, you built the indices, and then you went back and used the indices to index into the list. And so Python allows you to traverse over the list right from the start, you know. Why do you have to bother with so many irrelevant things? You know, just just go over the list. And so this is a Python anti -pattern. You know, you shouldn't do this. If you want to work with the elements of an iterable. Just iterate over it. And especially because some iterables, so there's some things you can you can traverse, you can go from the start to the finish.

12:23

And some of those things are not even indexable. So it's kind of you kind of need to do this for those cases. So just go with the general solution and with the Pythonic solution and type in the for loop. But then what if you want to print you know maybe the index and the elements? Then maybe you should really or maybe you do need to do something like this, you know, print the i and the elements. And I mean the element is really just the indexed value. But what that person was telling me, the person that was really next to me, really, really close to me in the metro carriage was that instead of doing all of this

13:09

all of this work, you know, where I find the range of the length and then I index into the in this case into the list What I can actually do is I can use two auxiliary variables and then instead of iterating over instead of just doing this Instead of just doing this, what I can do is I can enumerate my list. So this builds an enumeration of my list, and I get access to the indices and the elements all at the same time And just to show you this is not, so the enumerate of something, a list, a string, any terrible It's not that special, okay? It's not a weird thing, it's not black magic. So this is just an object, a special object, and if I turn it into a list explicitly, then I see that it's just a list of pairs.

14:01

the index and the value. So I took the hint of that person that was standing really close to me, I could even feel their breathing, or their breath, and it wasn't it wasn't as fresh as I had hoped. And I just changed my function, you know, because I could clearly notice the pattern where I have the range of the length and then the indexing happening And so I changed this to an enumerate and I deleted the extra parentheses and then for each index and character in my text Then what I can do is this is my character, and now I can evaluate this. And I can go ahead

14:47

and let's see, let me copy the print With the small test that I have and let me paste it and it still works. And by the time I'm I was done with this The metro was arriving at my station and so I had to put my phone in my pocket because I needed to reach for my wallet, you know, in order to be able to leave the metro and the station and etc And so I went outside, I resurfaced in in a different place in Lisbon, and well Maybe I shouldn't be proud of saying this, but you know I took my phone out of my pocket again and I was walking around with my phone finishing doing some finishing touches in my code. And then I woke up to the

15:33

to the zebra crossing because I needed to well cross the street. And I was waiting as I was waiting for the green light to to How do you say this? Is it to shift, to switch, um, to turn on? It's not to turn on, you know the traffic lights. As I was waiting for the green light to go to cross the street and it's just a side note I'm supposed to so my English is supposed to be good you know I studied English for a long time and I even did some fancy exams so I was supposed to be good at English so yeah you can see you can see how's that how that's going for me Yep, sorry for that. So I was standing

16:18

waiting for the traffic light because I'm a good citizen and I'm a good pedestrian. And I obviously didn't want to get hit by a car. So I was typing on my phone, you know, just fixing my code. And next to me was this person and they had some earphones on. They so these are headphones, they had those small earphones on, and they were clearly n listening to some really good music because They they were clearly vibing. They were doing, you know, that wavy movement with their heads, something like So they were clearly vibing and at some point they just take a look at me, you know, and then they take a look at my phone and my screen just for a split second.

17:03

But it was enough for them to walk up to me and say, you know, they they removed their earphones and they were like, hey, uh I'm sorry to bother you, but I think that you should, you know, maybe try to nest less stuff in your code. And then they put their earphones on again. And The traffic lights changed to green and so they just crossed. And I was just standing there, watching the person go away. You know, and I thought I was so good at Python, so how come everyone has all these interesting suggestions to me or to make to with regards to my code? Well, I just

17:49

I just crossed the street and then I started thinking about what that person have told me, you know So what what do they mean by like nest less stuff? So what does that mean? And then I I remembered that there's this thing called in called the Zen of Python in Python and The way you can access the Zen of Python is by typing import this in any console or in any script or whatever, and it just prints this Xenofpython. And the Zen of Python is this short um text that contains some guidelines that you can follow or suggestions that you can follow when writing Python code to make it more Pythonic or to make it more elegant or to make it

18:38

more readable And if you look closely, there's where is it? Over here. So the fifth line says flats, flat is better than nested. And I was thinking, well, I mean, this kind of sounds like whatever that other person was telling me. So what does that mean? And It struck me, it struck me, you know, there's Python has these try statements. I think you've you might have encountered them. And what they do is They allow you to write some code. Let's

19:23

the follow, let's see. So my list is was already defined. So they allow you to type some code But then also provide a a piece of code that runs in case there's an error that you were able to predict. And so In this case, for example, if my list is empty, then I cannot index into the list, and so I will get an index error. And if that's the case, then I just want to print that my list is empty. And in this case nothing bad happened because the list was not empty. But if I go ahead and if I change my list, my list to be empty, and if I run this. Then I get this piece of code is run because the list was empty.

20:08

I tried to index into it, I raised an index error, and here we are. Now the thing is when you have a try statement, sometimes you have some pre-processing to do before you do the actual work you need. And then you might also have some post-processing, you know, because you're doing something in your application, it doesn't matter. You might be, you know, the user might be logging in and then you are doing some stuff and then you're returning the you know a web page or the results of a request or a database query or whatever. And you write code like this. But then something interesting here is bound to happen because if the pre-processing or the post-processing throw

20:53

an index error. Then you're going to get up to this point. And I only have a print statement here, so this doesn't look um alarming, but if I have more complex logic in here. Maybe if I have something like a cleanup function in here, then the cleanup function is written with this index error in mind. You know, I have a very specific error in a very specific at a very specific point in time and I want to handle it in a very specific way. And if by mistake I catch an error that I shouldn't have caught then the pre-processing and or the post-processing and the cleanup they can get

21:42

mixed up you know maybe You can imagine that this was happening. You know the pre processing was maybe some something some authentication was happening in your In your app, and then your database was empty because you just created your website, and so you're trying to I I don't know index into a database in some way and you get an index error And you know, in in handling the index error maybe you return some I don't know some secured information that only logged in users should be able to see, but The database was empty, so how come the person is getting some some information that's only available to logged in users, you know, and all of this weird thing Unfolds in front of you, and the way you fix this is by

22:31

not nesting what you don't need to nest. So essentially the solution here would be to have the pre-processing out oops outside so the pre-processing needs to happen outside of the try statements And the post-processing, same thing. So you should try to nest as little code as possible. It's the same thing now. I don't want to run this, so can I open another cell? Or maybe let's let's just comment this. So this is not supposed to run because I don't have these functions defined. And it's a similar thing. Except I don't want this to print, so let's assign this to a sync variable.

23:18

Sorry about that. So now we can run this. I can run the cell, but it doesn't print anything. And it's the same thing with the with statements. Um sorry for the redundancy. In Python we have this this um with statement that allows you to open you know some file as F and then you can do something like you can read the contents of the file And then you can you know you can maybe find the lengths of the lines. So maybe you're reading the lines of the file and then the lengths are the length of each line for the line in the contents and then you print you know maybe the longest line has length and then you type in the max of the lengths

24:06

And you you even used F strings because you're really good with Python and you know that string interpolation is cool. You know, but the thing here is When you do this statement right here, when this statement is executed, you're opening the file and you're telling the operating system that you need the file because you want to read stuff from it. But by the time you're doing the computation, you can already release the file because you're not doing anything with it yet. And so Actually, what you would like to do is to have this unnested because then the width statement can conclude and you can free up the resources. as soon as possible, you know, and maybe this was a text file.

24:51

And in doing that, in not nesting this stuff you're actually one freeing up the resources sooner and two making it clearer why it is that you need to open the file. So with this it's very clear that I only need to read the lines of the file. And so let's do the same thing, let's comment this out because I don't have that file and I don't want to print all of this. And so you can keep going with this idea. And this is especially true in things that are deeply nested. So let me copy this over here and let me paste it over there. So this is just a function, it's a simple function, and you can see that I have things that are three levels deep, you know, in terms of nesting.

25:40

There's these things, this is the first level of nesting This is the second one and this is the third one. And as we go deeper into the nesting , we are introducing semantic dependencies. So the code right here This only runs if this thing is true. And this runs for each iteration of this loop. And this loop runs when this function is called. And if you remember what the crazy person told us when I was walking or why when I was waiting for the metro or for the subway Our brains are not that powerful, okay? They really struggle to handle too much stuff at the same time. And so whenever we can nest less

26:26

things. Then that's better. We want to nest less things because it allows us, it makes it clearer why the nested things need to be there because it it's it presents the intent. In a more clear fashion, and also it reduces the semantic dependencies of the pieces of code that we unnest. And so as I was reflecting upon the comment that the the person that was vibing with the music told me, I realized that actually the two statements on lines five and seven, I can actually unfold them like this. So I can do something like The modified character over here is the character dot

27:11

upper, and in here I want to append this And in here I want to do a similar thing and the modified character is the character in lowercase And when I do this, when I unfold the intermediate step of changing the casing of the letter or the character, I realize that Both the if and the else statement have a repeated piece of code, which is the append. And we don't like repeated code, so if I unnest the append operation I factor it out just a little bit and then the code looks like this. Now I was as I was

27:57

taking a look at this piece of code I was thinking I don't think this makes much sense, you know, I just I know I kind of de-duplicated a piece of structure that was repeated, but this is a fairly basic assignment and this was just such a simple append, so do I really need to do this? And I was thinking if this made any sense at all as I was walking into into a building that I well It it doesn't really matter. I needed to take care of I need to take care of my passport because I want to go to the United States. So I was walking into the the government building government building and I tripped Because I was looking at my phone and not at the stairs. And as I tripped my phone, it was on my hands

28:42

and it just fell off my hands. And I was getting back up. Thankfully I didn't hurt myself too much. I was getting back up and the security at the entrance of the building picked up my phone and they were handing it to me. But I'm sure they didn't do it on purpose, but they took a peek at my phone while they were handing it to me, and it was just enough for them to tell me They just told me this. They just told me, you know, from ETHET tools import cycle. And I realized that I was just I was making a movement with my hand that the camera didn't pick up, so but that's fine. So they were handing the phone over and they took a peek at my phone

29:28

and they looked at the code because the code was open the code was opened in the in my phone editor and they told me from ether tools import cycle And this was something that puzzled me. So before taking the hints, I just wanted to make sure that my code was still running. So I went and looked for the print statement And I made sure that my code was still working. And then I was just thinking about whatever they told me. So they said from ether tools import cycle. And I didn't know what this meant, so I imported cycle and then I asked for the help on the cycle function.

30:17

And then I just read this sentence. And the sentence said return elements from the terrible until it is exhausted then repeat the sequence indefinitely. And the terrible that they are talking about, it's just the sole argument to cycle. And then it struck me When I did this, when I did this and especially when I factored out the append statement It became quite clear that the if statement, its only purpose, is to decide what type of casing to do on each character

31:03

And because we are checking the parity of the number, so we are checking what's the remainder when divided by two, every other element or this Shifts every character, right? It's uppercase, lowercase, uppercase, lowercase, uppercase, lowercase, uppercase, lowercase, etc. It just goes on. It's always like this. It's always alternative And this is exactly what cycle does. It takes an iterable of things, and as you go through that iterable It just cycles between all of the things. So if you have an interval with length two, then you will be getting the two values.

31:49

went after each other. And I was I was so I was so excited about this because this this was essentially what I needed to do and so I wanted to test this out so I created some C that's a cycle with A and B. And remember that A and B are strings uh sorry, A and B R strings. This is a the this string is a it's an iterable and the elements are the characters. And so I wanted to test this out and so I wrote, you know, for each element in C, print elements And I was about to press enter, but then I remembered that I recalled that the help on cycle says that it repeats the sequence indefinitely

32:36

And I don't exactly have a control key on my phone, so I wouldn't really be able to press Ctrl-C, you know, to stop an infinite loop. And so what I did was I I did something like I zipped this with some numbers You know, and then I printed I printed these things. So the index and the element And I can show you the index as well. So as I was taking a look at this I was quite happy with the suggestion from the guard because we can see here that we have the

33:23

even numbers, they always get an a right here. And the odd numbers always get to B. And so I could use this cycle to cycle through my upper and lower functions. And in doing that I make it very clear, because that's what the cycle function does. I make it very clear that what I want to do is to keep alternating between the two functions, because it's it's right there, it's what the function does, it's it's the right tool for the job. And so I only needed I was only the only thing I had left to do was to find a way of specifying the two functions that I wanted. And so I thought let's do something like you know, the two functions that I need

34:09

It's a lambda function that takes a character and does the uppercase of the character, and another function that takes the character and returns the lowercase of the f of the character. And I thought, you know, this works. And so let's let's see if this works. And so I went ahead, I copied my code. And I pasted it in here. And now instead of going through the enumeration of the text, what we want to do is we want to replace all of this. And so what we want to do is we want to go over each character and function in what? In the zip. And the zip. is used to go over two iterables at the same time. So when you have two iterables and you want them you want to put them together and you want to go through them at the same time you use zip

34:55

And so I want I wanted to zip the text and the cycle of the functions and then To the characters, what I want to append is the function applied to the character. And now we uh we press enter, and if I go up I just want to look for the print and see if it still works. We go up, we run the function, and we see that it still works. But we can do even better, you know, we can make this a little bit neater. And the way we can do that is by noticing that this thing right here so typing something like hello

35:42

world dot upper The dot upper, this is just a string method. It's a function that I can call on any string. And this is the string class. This is what I use to build strings. If I check this, this is the method itself. So this is the function that I want to call. And actually, this thing right here is the same thing as Doing this. So I can already hold the function in my hand. I do not need to create a lambda function around it. You know, and so essentially what I mean is that if I take this, I can paste it in here and then

36:30

the functions that I have Those are just string. upper and string. lower. These are the functions that I need. And then I can go ahead and take my print statement And I can just check that this is still working. And then I take this piece of code and I submit it to Stack Overflow. Alright, so this is what happened. It was I know it was a crazy story, but you know, I just I just had to share it with you And you know, just to take a look at what everything that happened, let's so this was me showing you the code.

37:17

So let's take a recap at all of the refactoring that I did with all of the help we from all these, you know, anonymous people that just crossed paths with me that day. So we started out with this piece of code. You know, it it did it solve the task perfectly, it did what was asked, and it was simple. It only used simple bits, simple pieces. Or rather, instead of I don't want to call them simple, I want to call them um you know let's call them basic in the sense that they are not it's the things that you take a look at for the first time when you start with Python. It's you you start we you start with you learn len, you learn the return, you you learn how to do assignments

38:08

And then, because the the style of your code matters, we decided to add some more white space, you know, to to help the code breathe. And what we did next was we changed the names of everything essentially in the code because naming does matter. And after that, the the person on the metro uh told us to use enumerates. So we used enumerate. And then the person with the earphones that was clearly vibing told us to nest sparingly And finally, the guard at the

38:53

government building suggested that I leverage the Python standard library by importing Cycle. Which is essentially the tool that we needed to convey this idea that we want to cycle through two string methods And then we end up with this piece of code. Now The purpose of all of this is to show you that refactoring can and should be done little by little. It's perfectly fine. to feel overwhelmed when you have a code base that you need to refactor and even if it's just a single function, it can feel daunting.

39:41

especially when you're starting with programming. So don't be afraid of doing that. Python has many, many built-in functions, many functionalities, many features. That it's impossible for you to know all of them and that's perfectly fine. Just take the time to learn the core Python because It's not enough to know how to use the Django framework and build all these amazing apps if then you will struggle to build the core logic because you don't have the foundations of Python itself. So take the time to learn a bit a little bit of vanilla python and you don't have to learn it all at once because it's it's so much there's so much to learn, you know. Learn it little by little. And then don't forget the Python standard library

40:26

because it's very, very rich and it contains many many useful tools For your day-to-day tasks. And for example, Ether Tools is an amazing module to take a look at, and so is Funk Tools and plenty of others. So these are some references to some articles I have written where I explain How some of the features that I've mentioned and some of the reasonings that I followed in the refactoring. So these are articles, articles that I've been writing regularly. It's the Pythons, it's what I call the articles I've been writing these regularly and I do a lot of research. You know, I look into the the Python standard library and I look at the code and I look for the patterns that are in there

41:14

And I try to explain how they work and the reasoning behind them. So these are some of the references that I used to build this talk. And then just a little bit of, you know, if you want to learn more, all of those Python articles, I've been compiling them into an e-book that you can find on Gumroad. And the link is this, it's just gum. co. slash pythons so you can get the ebook with all of the pythons and the book is still growing because I'm still writing it um as as of when you're watching this if you're watching this at the conference at the DjangoCon conference And then if you if you'd like to learn more. Oh my gosh, my computer is oh my gosh, I hope this doesn't go.

42:00

I need to plug it in. No. Oof, okay, that's why that's why the probably you noticed that the animation was lagging because the computer needed power. Yeah, much better now. And then I'm sorry for this inconvenience. I was just about to say that. I'm going to post all of these links on or publish all of these links on Twitter at MathsPPblog and I I'm actually fairly active there you know in sharing Python knowledge and tips and tricks and whatever so if you wanna improve your Python knowledge just follow me on Twitter there's plenty of stuff that I I'm sure I can teach you and also that you can teach me Because as we've seen and as I've shown you in this talk, like everyone has something to teach you.

42:46

From the simplest idea to the most accurate but not well known import that will save your life. And Yeah, this is just an alternative way to get access to the articles. Sorry, I forgot that this was here. So it's the so if you go to my site, so that's mathspp. com slash subscribe, you can subscribe to my newsletter where I also send all of the links to the articles. You won't miss a single one. And then these slides will be uploaded to GitHub slash maths pp slash talks. So the slides should actually be there already as you're watching this. And feel free to reach out to me. I I do love meeting folks that are interested in Python, that are starting, or that are advanced users, and

43:37

just Just write to me an email, just drop me a line saying hi, I just watched your talk, and then give me some feedback because I want to I want to keep doing this, so I need to know what works and what doesn't. And also Last thing of all things, or second to last thing. Again, I do some Python training, so if you need any training whatsoever, reach out to me and we can talk. And then the very last thing There was an easter egg hidden in this talk, and it's not something that is easy to find, but if you think you found it Feel free to drop me a line or reach out to me on Twitter and if you if you found the Easter egg and if you got it right, I'll share it. I'll probably just I'll find a way to you know to shout out that you found the Easter egg.

44:26

So there was an Easter egg in the talk, and if you find it, please let me know. I don't think you will. So accept the challenge and do your best. So this was all from me. I hope you had a blast. I hope you learned something and I'll see you around. Bye.

Questions this talk answers

How much whitespace should I use in Python code to make it more readable?

Use whitespace around operators and assignments, along with occasional blank lines, so the code can “breathe.” These changes improve readability without changing the function’s behavior.

Discussed at 5:15

Why do good Python variable and function names matter?

Meaningful names give you labels for concepts and reduce the cognitive load of holding the code’s details in mind. Names should describe what an object or function represents, such as calling the function `alternate_casing` instead of using a vague name.

Discussed at 7:35

How do I use enumerate instead of looping over list indices in Python?

Use `enumerate(iterable)` when you need both each item and its index, for example `for idx, item in enumerate(items)`. This avoids generating a range and then indexing back into the iterable, and it also works with iterables that are not indexable.

Discussed at 10:47

Why is deeply nested Python code difficult, and how can I reduce nesting?

Deep nesting creates semantic dependencies that make it harder to see why each piece of code runs and increases the amount your brain must track. Move preprocessing and postprocessing outside narrow `try` blocks, release resources before doing unrelated work after a `with` block, and factor nested operations into flatter steps.

Discussed at 22:31

How can I alternate between uppercase and lowercase transformations in Python?

Use `itertools.cycle` to repeat the sequence of transformations, such as `str.upper` and `str.lower`, and combine it with the input text using `zip`. This expresses the intent directly instead of checking whether each character’s index is even or odd.

Discussed at 30:03

How do I apply different functions to corresponding items from two iterables in Python?

Use `zip` to traverse the iterables together, such as pairing each character with the next function from a cycling sequence, then call the function with the character. Existing methods like `str.upper` and `str.lower` can be passed directly rather than wrapped in unnecessary lambda functions.

Discussed at 34:09

What is a practical way to refactor Python code without getting overwhelmed?

Refactor incrementally: improve formatting, clarify names, replace index-based loops with `enumerate`, reduce nesting, and then look for standard-library tools such as `itertools.cycle`. Learn core Python and the standard library gradually rather than trying to master everything at once.

Discussed at 38:53

Note: We understand that names change, people change, and bodies change. We respect each individual's journey and privacy. If you have any concerns about a video or need us to remove content, please don't hesitate to contact us. We will handle your request with care and promptly address any issues.

More videos from DjangoCon US