Messing with the GC
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Jan 19 11:44:04 EST 2013
And further thoughts...
On Sat, 19 Jan 2013 14:47:16 +0000, Jens Thoms Toerring wrote:
> Hi,
>
> triggered by some problems I had with PySide I got a bit
> confused about what the GC may do in certain situations. Here's a small
> test program I cobbled together:
>
> import sys
>
> class X( object ) :
> def __init__( self, parent, cnt ) :
> print( "In constructor for {0} {1}".format( self, cnt ),
> file = sys.stderr )
> self.parent = parent
> self.cnt = cnt
>
> def __del__( self ) :
> print( "In destructor for {0} {1}".format( self, self.cnt ),
> file = sys.stderr )
>
> def foo( self ) :
> print( "Before", file = sys.stderr )
> self.parent.z = X( self.parent, 2 ) # Is this bad?
> print( "After", file = sys.stderr )
>
> class Y( object ) :
> def __init__( self ) :
> print( "In constructor for {0}".format( self ),
> file = sys.stderr )
> self.z = X( self, 1 )
>
> def __del__( self ) :
> print( "In destructor for {0}".format( self ),
> file = sys.stderr )
>
> Y( ).z.foo( )
>
> Have a look at the line with the comment.
You mean this line?
self.parent.z = X( self.parent, 2 ) # Is this bad?
> At this point the only
> reference in existence to the X class instance, of which a method is
> just being executed, goes out of scope.
I don't understand this, but to the extent that I do understand it, I
think you are wrong.
What do you mean, "the X class instance"? If you mean the class X itself,
no, that survives until both the class itself is deleted and every one of
it's instances. If you mean "self", no, that doesn't get deleted by that
line at all.
> Thus I would assume that the GC
> could now kick any time, possibly even before the following call of
> print() or before the method call returns. That, in turn might result in
> a crash of the script.
It would be a pretty crappy garbage collector that collected objects
while they were still being used.
> Is my assumption about this flawed and there are no potential dangers?
> Perhaps with
>
> Y( ).z.foo( )
>
> a temporary second reference is created that keeps the GC for removing
> the X instance...
I'm not even sure what X instance you are referring to, or why you think
it is going out of scope.
--
Steven
More information about the Python-list
mailing list