Rock Solid Python with Python Typing Transcripts
Chapter: Typing Guidance, Patterns, and Advice
Lecture: Collection Advice

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Final thing I wanna talk about are collections and their contents. This is a beautiful closet setup, isn't it? I mean, okay, maybe it's from a store,
0:12 but look how nice it looks. It's got all these different colors and all the variety. And as a person, I look at this and go, oh, that's just great.
0:19 Look how creative, how interesting. But if you were a collection in the type system, not so much.
0:27 You probably would feel better if it looked like this. All the same, it's all just these like no-armed gray sweater things
0:36 because it's a collection of no-armed gray sweaters. You wanna think about that in your type system for collections as well.
0:44 So something like this, these things, we have a list of, and then what goes in that bracket? If that's always the same thing,
0:53 you've got tons of information to work with. It's very well constrained. But Python types, they'll take anything. Like I could say, you know what?
1:02 Things actually is a one numerically, then it's a string, then it's written out word two, then it's a list of ones,
1:09 and then it's a user with ID five and so on. It's great that the Python has this flexibility. However, what do you do
1:18 as you go through these different things? How do you process it? Like how do you treat the first and the third thing the same?
1:23 Their strings are without the text and then the ones a number and then it just gets worse from there. So if you wanna express this, you can,
1:34 you would just have to say list of any, but you should try to avoid this. There are certain times of like hierarchical data
1:41 that is just so hierarchical and diverse that you just have to embrace the dynamic nature of it. Think JSON, complex JSON responses from APIs.
1:52 But in general, in general, try to make your collections all the same thing. Make them those boring gray armless sweaters
2:01 and don't make them have a lot of variety because if they're all the same thing, then all of a sudden it becomes very easy
2:08 to reason about its contents. Like when you loop over it, what is the thing in there? Well, it's a number, great, or you index it out or whatever.
2:16 Certainly there's times when it doesn't make sense, but aim to have collections be homogeneous,
2:22 homogeneous, not heterogeneous, containing the same type throughout.


Talk Python's Mastodon Michael Kennedy's Mastodon