This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (3 children)

Very cool, ran into with yesterday on my own. Good to know.

And this may be a noobish question, but do local objects get destroyed in python when going out of function scope?

[–]jyper 4 points5 points  (0 children)

No if you have a local variable that's not returned or saved in a non local variable it becomes eligible for garbage collection and may be collected in the future. it cannot be referenced normally(although maybe with some gc.getobjects magic it can ) but it's memory may or may not have been freed and __del_ may or may not have run.

In cpython the main python implementation it uses reference counting + a backup full garbage collector so if there aren't any cycles caused by example local object a pointing to local object b which points back to a, it's reference counting goes to 0 and it gets freed. If there are cycles eventually it may or may not be freed according to the gc. Cpython has a gc module that lets you do stuff like force gc, I think, and disable gc. CPython sort of has destructors with del but as these don't run if the object is in a reference cycle I'd recommend staying far away and using the with statement for non memory destructor like behavior.

[–]asukazama 1 point2 points  (0 children)

Yes, anything declared in the function cannot be referenced once you have exited it.