When is the memory from g freed up?
It depends on what you mean by "freed up".
From Python's point of view, it's not. As long as you have some reference to that list that you could use at any time (which you do, in the variable g
), it can't be freed up. Otherwise, what would happen if you later tried to use g
? But Python's point of view isn't based on the actual RAM chips sitting in your computer. Your OS lets each program pretend that it has a huge flat chunk of more memory than it could ever need.* Of course that isn't actually true; see below for more on this, but let's stick with Python's view for now.
If you give up all references to that list—e.g., by returning from the current scope, or assigning something else to g
, or doing del g
(all assuming that's the only reference), then all the memory used for the list can be freed. (In CPython, it will usually happen immediately; in other implementations, usually just "soon".)
But "freed" doesn't mean "returned to the operating system". In general, it will be kept around in a freelist (actually, a few different levels of freelists), on the assumption that if you wanted 3GB now, you'll likely want 3GB again, so Python might as well keep the storage around, because that's faster than re-allocating. (So, if you'd released f
, before creating g
, then g
would take most of its 2GB out of the freelist, and only allocate another 1GB.)
But "not returned to the operating system" doesn't mean "wired to physical memory". And here's where we get to the difference between Python's view and the hardware view. If you've got only, say, 8GB of physical RAM, and 6 programs that each have 12GB of data at the same time, where does the extra 64GB fit? It gets stored on disk, and reloaded from disk the next time you try to use it. Normally it'll do a pretty good job of this.** SO, if you never touch that 3GB again, and some other program on your system needs some memory, your OS will probably page it out of RAM, and never page it back in.
On a related note, you also never close
your file objects. That means the file handles are still open until the garbage collector notices that nobody's ever going to use them again. Again, this will usually be immediately in CPython, usually not in other implementations. But don't rely on that. close
your files—or, better yet, use a with
statement.
* Insert 640K joke here.
** But it's very easy to either maliciously or accidentally prevent it from doing a good job. For example, create a list of 30 billion ints, and keep randomly changing random values, and your OS will spend so much time swapping pages in and out that it can't do anything else…