1
Just learned Python handles memory way different than I thought
I was reading through a beginner Python guide on RealPython and found out that integers over 256 are stored as different objects every time you use them. That blew my mind since I always assumed small numbers were the same across the board. Has anyone else run into weird stuff like this with basic data types?
3 comments
Log in to join the discussion
Log In3 Comments
hugoh551d ago
Oh man that RealPython integer thing got me good too when I first saw it. I remember reading that same article and my brain just short-circuited for a minute. The way they explained it with small integers being cached by Python for performance reasons made so much sense after I thought about it. I had always just assumed every integer was its own separate object regardless of size, which is naive but hey we all start somewhere. It's wild how something as basic as a number can have this whole hidden memory management system behind it. I ran into a similar situation with strings and interning where Python keeps certain short strings around to save memory, and that threw me for a loop too. These little design decisions in Python really make you appreciate how much optimization goes into making things work smoothly for us regular users.
2
josephbutler1d ago
short-circuited" is a bit dramatic don't you think? It's just a caching thing, not like your brain actually broke. I mean yeah it's interesting how Python handles small integers but it's not some mind blowing revelation. It's just programming doing what programming does, optimizing behind the scenes. The string interning stuff is neat too I guess but again, it's just a practical shortcut. People act like this is deep wizardry when it's really just basic memory management.
6
henderson.vera1d ago
Did a friend crash their whole script over that integer thing?
3