- Podcasts
- Python Bytes
- #270 Can errors really be beautiful?
About this episodeTopics covered in this episode: A Better Pygame Mainloop awesome sqlalchemy ThreadPoolExecutor in Python: The Complete Guide Chaining…
- A Better Pygame Mainloop
- awesome sqlalchemy
- ThreadPoolExecutor in Python: The Complete Guide
- Chaining comparison operators
- Create Beautiful Tracebacks with Python’s Exception Hooks
- Extras
- Joke
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
#270 Can errors really be beautiful?
Hello and welcome to Python Bytes, where we deliver Python news and headlines directly to your earbuds. This is episode 270, recorded February 9th, 2022. I'm Michael Kennedy. And I'm Brian Okken. And I'm Dean Langsam. Dean, so great to have you on the show. Thank you. So often you help me with that start in the live chat.
I know you're a big participant in the show, so we pulled you in and now here you are. Welcome. Thank you. Thank you. I've been a fan actually since episode one. I've been hearing this weekly. That goes back years, like five years or something. Yeah, it's about five years. I remember I moved apartments back then and I listened to Python.
I didn't know Python as well back then. And I actually grow with the show. So that's very nice. That's fantastic. That's incredible. We've heard that from other people and that's just like mind-blowing to me. But yeah, it's cool. Yeah, I was taking like intro to data science classes in Coursera while listening to the show.
And now other people call me a senior Python. So that was very nice. That's fantastic. And it does go fast. Yeah. So awesome. Thank you so much for joining us on the show. It's awesome. Before we get into it, I also want to say this episode is brought to you by Datadog. Check out their awesome stuff at pythonbytes.fm/datadog.
I'll tell you more about that later. Right now, Python, I want to hear about a better Pygame loop. Brian, tell us about it. Yeah. So this is an article from Glyph. And Pygame is a package that's used for game programming a lot. And it's, I mean, a lot. And programming games is definitely, I think, it's one of the things I tried to do early on when I was a developer.
Right. You're not waiting for the V sync 60, a hundred frames a second, whatever it is. Right. Yeah. So, and that can cause glitches in the game and it doesn't, it doesn't look as good. Py game does allow a V sync option, but apparently there's like some problem with that. So what really there's a, the article walks through both of these, both of these problems and the V sync fix, but, and the problems with that.
But the end result really is he's got, it's actually interesting, interesting discussion about like really what's going on in py game. And he talks about like that, that there's really three jobs going on in the drawing and a game logic and the input handling all at once. And so this is a three thing.
It's probably a good idea to do maybe async stuff. So things can work together. And, and the solution he came up with is still, I mean, it's definitely a larger loop, but it's not that big of a loop more complicated. And it's an async version to have some sleeps in there with some delays possibly, but a better loop for gaming.
And it's, it's almost always the same. Like this looks great as a way to tell me what I should be doing. And maybe the next step would be create a class that I just override, do the AI logic, draw the screen and just let that like not even be something I ever see. So this is ripe for a little bit of hiding away even this cool stuff.
That's true. Maybe, maybe Pygame could extend a better built-in loop to hook into or something. Yeah. Yeah. I always think about, I always, I'm not actually used, do a lot of gaming on Python, but I always think about browsers, which are also kind of a loop that runs forever and renders stuff on your screen.
Maybe this could attract more people into writing small games in Python. Yeah, absolutely. My thought is if you just sort of abstract that away, it's just 2D stuff, right? Which it's pretty easy to get into. I just listened to or watched a Netflix series called High Score, which is the history of video games going like way back to the Atari 2600 and Asteroid and whatnot.
You can write that and that's super fun. But you can do a lot of stuff with just sort of text-based little fun story adventure type stuff as well. I got to check out that Netflix series. That sounds great. Yeah, yeah. I was just helping a friend writing like this small game and he's written this like with one thread and everything for this school project.
Yeah, absolutely. There's a lot of nice comments out in the live stream. Anthony says, I teach Pygame in my code club after school class. Smart kids, Pygame is great. So is Arcade, which is an alternative, an OpenGL-based alternative to Pygame. That's very cool. I do think having something visual for people when they're learning, it just, it reinforces things so much, right?
I want to talk about SQLAlchemy. SQLAlchemy has been getting a lot of attention lately, and that's super cool. Mike Bayer released SQLAlchemy 2, which was the first async API version. So now you can use async and await with SQLAlchemy, which opens up lots of possibilities. Sebastian Ramirez released SQL Model, which is like a marriage of Pydantic and SQLAlchemy, which is also super neat.
But there are many other things that you can do with SQLAlchemy that are really handy. So as all the awesome lists go, here's one for a curated list of SQLAlchemy. Now, first, just a word of warning from what I can tell, including the PR that I added yesterday, all the way back to the one in June 2020.
It doesn't seem to be getting a whole lot of love, which is unfortunate. So it seems like it might be sort of stalled out. But that said, it's still a really good list of things. So I'll pull out a couple that I think are nice here. Which ones did I want to highlight? The first one is called Continuum.
SQLAlchemy Continuum. And this is versioning. So imagine you would like to have a history or a record of changes to your database. Like maybe this is some sort of financial thing. And if you see changes, you want to be able to say, this person made this change on this date when they said, you know, update.
So if you want that, SQLAlchemy Continuum. It's just like one of the many, many, many things in here, which is pretty awesome. Another one I wanted to highlight is UTC. So one of the challenges that people often run into is when you're storing stuff in the database, dates in particular, what time is that?
Is that the time of the user who might be in a different time zone than the API endpoint that it was running at? Right. So it might be nice to be able to store time zone aware things and store them as UTC values so they're always the same. And then you can convert them back to the time zone, which is pretty cool.
So that's kind of a grab bag of them. Let's see. One also is called File Depot. There's cool stuff for processing images. You've got File Depot, which is a framework for easily storing and serving files out of your database on the web, as well as SQLAlchemy Image Attach, which is specifically about storing images in your database, which, by the way, we do, Brian, on Python Bytes.
So if you want to add full-text search to your model, you can add, use this. And then it only supports Postgres because I'm sure it depends upon some core element there. But you can also do another one from MySQL as well, which is pretty cool. And then the last one is Schema Display, which generates basically graphs of your models and how they relate to each other, stuff like that, which is kind of neat.
Nice. What do you all think? Cool stuff, right? Yeah. Very cool. Yeah. So if you're really bought into SQLAlchemy, you owe it to yourself to just flip through this list to just go like, wait, it can do that? I had no idea that it could do that, right? And just sort of see what are the other things that people built on top of here that I think would be super, super helpful.
And by the way, my PR was really to say there's a layer called thin abstractions. And it says, you know, under the thin abstractions, we really should have us some SQL model because that thing is super popular straight out of the gate, right? So people should check this out. It's already got almost 7,000 stars and it's, what, a month old or something?
I'm a data scientist and we need to take many queries at once and get them as Pandas data frames and save them to disk and later take all of them and work with them. And instead of writing, like sending them sequentially, I wanted to send a bunch of them together. And the bonus thing I found that is that when you release them to a threading, if you don't lock the threads or you don't wait for the threads, you can actually still work with the Jupyter notebook while waiting for the queries.
It's a very long blog post, so you could kind of read it as an e-book or just access the stuff you need because it's like, I don't know, a two-hour read maybe. And he explains everything from the beginning. He explains what are Python threads, how to work with them. Then he introduces the Threadpool Executor, which is a more convenient way to use threads.
And yes, there are questions. The questions like, how do you stop running? There's a lot there, yeah. There is a lot there in this article, isn't there? Yeah, it's a lot. It's a lot. But the thing is, you can come back later and just take the stuff you need. Like I remember, I know I'm working, then I can ask myself, how do you set a chunk size in map?
Well, it says there that you don't because that's for the process pool. But then I have another question. Maybe how do you cancel a running test? And the answer is that. So I think that's a good thing to have like to quickly access when you need to. And it finishes off with like, what's the difference from asyncIO, from threading.thread, from process pool executor.
So that is a very helpful guide, very complete. And the entire blog actually explains, like it's an entire blog dedicated to the threading pool executor and the process pool executor. I love that it's covering the thread pool and process pools because it's easy for things to just completely get out of control.
Each thread takes a lot of context switching to switch between. And they take a decent amount of memory and all sorts of stuff, right? Through the thread pool, you can say, queue up the work and run 10 at a time. Same for processes, which sort of sets an upper bound on how much concurrency you can deal with, right?
Like, after maybe some group buys and limitations and stuff like that. And I want to take the data frame and save it. Right. And then once I have the entire data from all the queries, I want to join them or maybe do some, I don't know, some processing and then join everything. The thing is, after, like, 10 of those came back, I have a sample of my data that I can work with and try to manage and then have a code written.
And while the other stuff is still written, I want to have that, like, I can play with it. So if I release the other things to the threads and they work in the background, the main thread of the Jupyter Notebook is open. And you can start working on the same notebook. Before then, I used to, like, open a notebook that's querying stuff, open a notebook that I'm playing with and, like, see that the file paths are the same.
Yeah, that sounds really good. I'm sure there's a lot of concurrency and parallelism in the data backend. It's just how do you sort of access that from Python, right? So how do you issue all those commands? Excellent. All right. Let's see. Brian, anything you want to add before I talk about Datadog?
No. Some comments, like, Sam, Morley, concurrent futures is a much less painful way to work with them at a higher level. So maybe we could get an article on concurrent futures on the upside sometimes. Yeah, for sure. So the thread pool executor gets you back futures. And then part of what's explained in the blog post is how to work with futures, like, as completed or sequentially or, like, you decide your strategy, but you work with the futures.
Nice. Okay. Cool. Yeah. Nice. And, of course, requisite shout out to Unsync, which is all sorts of awesome for this stuff. Unifies the API for direct threads for processes and AsyncIO. But what I want to tell you all about now is Datadog. Datadog is really awesome. You should really have insight into your applications.
And that's what Datadog brings you. So Datadog is a real-time monitoring that unifies metrics, traces, logs into one tightly integrated platform. Their APM empowers developers to identify anomalies and resolve issues, especially around performance. You can begin collecting stack traces, visualize them as flame graphs, and organizing them into profile types, such as CPU bound, IO bound, and so on.
You can search across the full stream of all the traces over the last 15 minutes. So try Datadog APM for free with a 14-day trial. And then Datadog will send you one of these very cute doggy t-shirts, which who wouldn't want one of those, right? So visit high-dom-by-stud.fm slash Datadog or just click the link in your podcast player show notes to get started.
Thanks, Datadog. And, Brian, back to you. Back to me. I was, I'm going to apologize whoever tweeted this, but somebody tweeted this out, a link to this article, and talking about chaining operators. So this is an article by Rodrigo Serrao. Py don'ts? Yeah. So I don't know what the py don'ts are about.
Just, I don't know. Maybe he started blogging about things you shouldn't do in Python. Anyway, this article is called Chaining Comparison Operators, and I use chaining all the time. Mostly, I use it for simple things like, oh, let me find one. A is less than B, less than C. So ranges, like min, you know, my X value is between min and max.
Yeah, that's really nice. Yeah. My hint on that, like, just tip for anybody doing that, always do them less than. Don't do greater than, because it's hard to do that. Anyway, so keep them like that. But this article is talking about other stuff. So this is pretty easy to think about, like the less than operators.
So A is less than B, less than C. Is that really the same as A is less than B and B is less than C. It is that combination. That's what chained operators are. And the importance there is it doesn't really work for some operations. And it gets into, like, the equal operator. So you can do A equals B or equals C, which means they're all equal.
Great. What about not equal? Does that work the same way? And it doesn't, because if you've got, like, A is not equal to B is not equal to C, it doesn't mean they're all different, because A and C still could be the same and have that pass. So this article, if you're working with chained expressions, which I think you should, if you're doing complicated things, it's way, I like it better than doing, having a bunch of ands in there, as long as that you can keep it readable.
Yeah. My favorite one of these chainings, like, X, you know, 7 less than X less than 10. Yeah. Something like that. That's nice. My favorite is converting X, if X is not none, else Y to just X or Y. Boom. That's so clean and so nice. And I never, coming from a C++ background and C#, I never thought that was possible.
That's great. Yeah. Dean, what do you think about this? I love it. I use it a lot. It didn't always work. I think it's still not working with Pandas data frames or Pandas series and arrays. And I do wait for this to finally work. Arrays, when you do an array, like in NumPy or Pandas, when you do an array, it's less than some number.
It returns a new array with true, like a Boolean array with true and false. And last time I checked was a few months ago, but the last time I checked, it didn't work. I couldn't do one is less than the series is less than two and get the Boolean array. So I'm waiting for this, but I love the concept a lot.
Yeah. All right. I want to give a quick shout out to Rich because it's one of our episodes. So we talk about Rich. I was going to talk about Anthony Shaw, but I didn't have enough information. So, I mean, he's the other person who needs a shout out in every show. So I want to talk about this article highlighting some tools by Martin Hines.
Yeah. Martin Hines. Yeah. Well, creating beautiful tracebacks with Python, done exception hooks. So two things that I want to point out here. One, Python has an exception hook mechanism, which is pretty cool. So what you can do is you can create a function that has this signature of exception type, the actual exception and the traceback.
Yeah. So depending on what you want to do, like you could say, well, we're going to store all the errors. Like, let's imagine here's a scenario where you might make use of this. I'm going to create an app and I'm going to send it out. I'm going to use Py2App or Py2XE or just, you know, let people install it somehow.
So I got a question before I go on. Yeah. So this doesn't catch the exception. It just, it doesn't interrupt the flow. It just, it just gets called when it happens. It doesn't, it doesn't catch the exception. It lets you basically change what kind of output comes from Python. So if you just wanted to print out like, here's a file where there was an error and here's the error message.
Okay. Like you could do that, right? Or the type and then the message. I'm just noting the, noticing the example doesn't re-throw it. So you don't have to do that then. No, I don't believe so. And I'm not a hundred percent sure. I think the app, I think the process still ends. If it's just a regular running script rather than a web app.
Oh, yeah. Okay. Nice. Okay. So it's easy enough to do. Like, for example, they have this function that they call that caused an error. And all you see when this crashes is there's a trace back. This file, this line in this module, here's the error message, right? Instead of the huge stack trace that might scare people.
But the real interesting part is if you go and look at some options. So there are five, I believe there are five libraries mentioned in here that do really cool stuff for solving this. The first one is by Will McGugan's rich library. So you can just go from rich.traceback, import install, and then say install.
Show locals is true. And then this also basically installs one of those global exception hooks. With the benefit being when you get the errors, what you get is a nice rich output. It's super pretty. It's pretty and it's useful. I mean, it's color highlighted so you can see where the error happened, but it also will print out in a really nice way with formatting and highlighting the locals, right?
So what values were passed to that function when it's crashed? Well, here's a little table of those and so on. So this is really easy to identify. And at the very bottom, like a nice clear way to like, okay, what happened? So you can do this super simple version here. And there's also some manual ways to make rich print this type of stuff.
And there's pretty errors. Check out pretty errors. This looks pretty good, right? It's got a lot of like bold and highlights. You can really call out the error messages and the functions involved in the modules involved. Here's one for you, Dean. The built-in one to IPython. It has ultra TV for ultra traceback.
I think this uses the 310 part or something like that. Oh, awesome. Yeah, that's cool. We'll hear more about it when we talk about IPython 8 as well. Cool. Yeah, so that's built in, kind of if you're already on the data science stack. And then finally, stack printer, which you can give it a traceback and it will print that out.
So you can sort of do like rich, you can say set exception hook and give it a theme like dark or whatever. And then it does this pretty nice printout as well. So these are all great. I'm personally liking the rich tracebacks version best, but this is really nice. Yeah. Connor out there in the audience says, wow, using show local SQL tree would have saved me hours and hours of time.
And you and me both. Yeah. I feel the pain. I do too. So because a lot of times you're like, I know it crashed and it says none type does not have attribute, whatever. But like, why is it none? I need to go back three levels, right? Like, yes, it's so good. And then you find out you just forgot to return from the function.
Yes, exactly. I was just debugging a test failure the other day and pytest has the option to throw a local. You can show locals with a crash or with every failure. And I forgot that the particular thing I was testing had like variables that were storing thousand element arrays. It just like went on for me.
I believe the, I believe Rich's has a truncate variables where it'll do an ellipsis or something like that. I think. I mean, yeah, I'm not a hundred percent sure because I've been looking at all five of these Will's in the chat. We'll have to ask him. Will's in the chat. You'll have to give us a shout out.
Will, I think, I think truncate is out there, right? I'm not a hundred percent sure. I think of how can I actually, so I talk with databases and sometimes the errors from the databases are like this big Java stack, Java trace. And then you need to like a lot of go a lot of apps. Sorry, something, some noise here.
Sorry. You need to go a lot, a lot up in the browser to actually see the error. And if I could just shut it down and just give me the Python stuff. Cool. Yeah. I don't know what setting you set for that, but certainly with this mechanism, you could set it up so that like if the word Java appears, you just stop.
Yeah. You just stop going back. Yeah. And Will says, yes, that's right. Thank you, Brian, for pulling that up. Yeah. Yeah. You can truncate it so that printing won't go completely insane because it could be gigabytes. I mean, it could be out of control, right? Yeah. Yeah. But I mean, even if they have a like reasonably large limit, sometimes it's just like, oh, I forgot that huge array was there and it's hard to see stuff.
And I'm a data scientist, but I also love testing. The thing about testing with data science is sometimes it's not that clear what you should test for. Right. because sometimes some things we do are stochastic and then you could not actually test for stuff or stuff like that. So this blog talks about like the art of testing because sometimes like the it's not clear what you should test.
And the more experience you get, you can actually see what's coming your way. And he talks about like data validation and he is throwing many packages that could help you. Packages like Pandera and Great Expectations that I think we've talked about before in the podcast. And also like the NumPy has some stuff like is closed.
Just think like where does this thing could hurt me? He gives an example. Maybe if I'm trying to join two data frames and I think they have the same shape, I want to check if they have the same IDs. So that way I know that the join works correctly. So he asserts that the length of the IDs is the same within the two data frames.
And this is not even like real testing, we would say. It doesn't use some testing framework. It just says like write it within your code. It then continues to like hypothesis, which basically bombards the functions with a lot of ways to actually try to fail it. It continues with some other packages and eventually goes into a pytest and shows like how it would work with pytest and with like an approach that I haven't heard of.
Yep. And it's what when you do in science or data science. I'm glad he talks about structure because a lot of people that get into testing get get these giant tests that do do a little work, test something, do a little more work, test something. And then if it breaks, you're not sure what where the failure is.
I know this will be helpful to people. It's really I always wonder about testing data science stuff and machine learning things and so on where you get small perturbations, but they're fine. It's off by one millionth of some unit, but that's totally good. Those are equal. But it takes, I think, an extra level of thinking about it.
So much people focus on, well, how do you get rid of your dependencies and how do you make sure that you don't talk to the real database when you do this? And that's one aspect that people focus on. But this working with science-y type stuff is its own specialty. Yeah, I think the entire community is a fairly new community, although it's not as new as it was.
But then you realize that they got donations of like a few hundred dollars within 10 years. And then after the Log4j, suddenly they got a thousand. So this, I think it shows you how the money could help open source stuff. And maybe if you use some package in a company, in some corporate, maybe try and think how you can give back money.
Or even if you give back code, if you free up your developers to actually contribute, this is awesome. And the half thing just mentioned because it talks about the traceback. It shows that you can now see it's like colored. You can see on the screen, it's called the part where actually the arrow was, it's colored now.
So it's very nice to see. Like the example shows you, you add the function three times, but only it fails on just one input of them. So it shows you which of the three times the function failed. Right. You call it the same thing like foo of zero plus foo of one plus foo of two. And it's the middle one that failed, not just line seven, but the second invocation with the value one where it failed, which that's awesome.
Like, we know how to do. Yeah. Yeah. That's really interesting. There are certain things in the standard library. You're like, yeah, yeah. I know that's there and you could use it, but you probably shouldn't use it. There's like so many better external choices that are so good that it would be kind of silly to bite them.
But there are some other parts that are actually really needed. So maybe deprecate half of it. Yeah. I'm not sure if I'm about deprecating it. But, you know, it's one thing to say there are better choices. And we as a community recommend you probably just don't use this. But to deprecate it means to people who would rather go with a dependence, a lower level of dependencies, you're giving them warnings that they shouldn't be doing this when maybe, you know, it's unlikely it's going to actually vanish.
And some of the other parts that maybe people want to stop supporting. That's something very valid. Python still is an open source project. And we can make those decisions. Yeah. Victor actually says there are 40-year-old security issues in URL lib. So maybe it's better to use something outside of it.
Bring requests in. Vendor a little bit of it in so it does what URL lib does. And just go look. Okay, this is the latest, greatest that we got. And everyone's been looking at requests already. I don't know. It could be interesting. Yeah. And then Brandon out in the audience points out there are also maybe environments where you can't install dependencies for security reasons.
I brought this up last week. I'm currently not writing a book. Yay! So I want to write more blog posts. So one of the things I wanted to make sure that my blog migrated to pythontest.com. And now it has a blog setting. And I like it. It looks pretty, too. Instead of just pulling everything over from my old WordPress blog, I'm trying to edit it.
So I'm up through 2012. I'm going to go oldest to newest and gradually do things, bring things in. So that's one of my side projects I'm working on. Yeah, that's a great side project. Nice. What's that running on? Is that like some static site generator or other hosted thing? It's Hugo hosted by a free Netlify account.
Yeah. Netlify is pretty awesome. All right. I got a couple of things I want to give a quick shout out to. Yeah, Brandon. Brandon had the same question, but we got it. All right. First of all, I have two new my Python shorts, two new versions, two videos from there. I got beyond the list comprehension.
So basically set and dictionary comprehensions. Fun stuff. Nice picture. Thank you. It's a little and it's like just a screenshot out of an animation. And then combining dictionaries. Python 310 way is the title of the article. It really should be 3.9, but I kind of want to communicate like if you're on the latest Python, how should you be doing it?
It came out in 3.9, the features that are actually in there. Anyway, the pipe stuff. Dictionary 1, pipe, dictionary 2, pipe, dictionary 3, which is all fun. And then I wanted to talk about a feature over on pypi.org. I don't even know how I found this. Probably just like an accident, like bump the keyboard or something.
Nice. I don't even remember what my joke is. So that's good. That'd be fine. I mean, you're new to us all. You ready? Yeah. All right. Yeah. Here we go. Oh, yeah. This is another one of these sort of like frustration type of things. That's great. This comes from the Programming Humor Twitter account.
They're going, oh, I hate this job. I hate my life. Why is this happening to me? Never mind. I misspelled a variable. Good to go. Yeah. Linting. Yeah. Linting is good. Linting. Indeed. Indeed. If you just flip through the Programming Humor one, it's pretty good. You know, this eight-year-old is learning Python after dealing with the syntax bug.
Exactly. There are uses. They're rare though. All right. Well, fantastic. That last one. See? Yeah. It shall not be spoken, but it's good, right? Okay. There's a lot of good stuff. I recommend people go flip through that Twitter account. Nice. Brian, thank you. As always, it's good to be back with you.
It's good to be back. And Dean, thanks for coming on this side of the presentation and joining us for the show. Thanks for having me. Thanks for listening to Python Bytes. Follow the show on Twitter via at Python Bytes. That's Python Bytes as in B-Y-T-E-S. Get the full show notes over at pythonbytes.fm.
If you have a news item we should cover, just visit Python Bytes.fm and click submit in the nav bar. We're always on the lookout for sharing something cool. If you want to join us for the live recording, just visit the website and click live stream to get notified of when our next episode goes live.
