I don't have an example of code but I'm curious if you do bad coding practice, is that possible?
views:
229answers:
4Of course you can. The typical example of a memory leak is if you build a cache that you never flush manually and that has no automatic eviction policy.
In the sense of orphaning allocated objects after they go out of scope because you forgot to deallocate them, no; Python will automatically deallocate out of scope objects (Garbage Collection). But in the sense that @Antione is talking about, yes.
It is possible, yes.
It depends on what kind of memory leak you are talking about. Within pure python code, it's not possible to "forget to free" memory such as in C, but it is possible to leave a reference hanging somewhere. Some examples of such:
an unhandled traceback object that is keeping an entire stack frame alive, even though the function is no longer running
storing values in a class or global scope instead of instance scope, and not realizing it.
Cyclic references in classes which also have a
__del__method. Ironically, the existence of a__del__makes it impossible for the cyclic garbage collector to clean an instance up.poorly implemented C extensions, or not properly using C libraries as they are supposed to be.
Scopes which contain closures which contain a whole lot more than you could've anticipated
Default parameters which are mutable types:
.
def foo(a=[]):
a.append(time.time())
return a
And lots more.....
The classic definition of a memory leak is memory that was used once, and now is not, but has not been reclaimed. That nearly impossible with pure Python code. But as Antoine points out, you can easily have the effect of consuming all your memory inadvertently by allowing data structures to grow without bound, even if you don't need to keep all of the data around.
With C extensions, of course, you are back in unmanaged territory, and anything is possible.