[C++-sig] C++ chain method works unexpectedly in Python

INADA Naoki songofacandy at gmail.com
Mon Apr 18 04:07:40 CEST 2011


Python Interactive shell stores result of an expression to a variable
named '__builtin__._'.
So, ``del _`` may help you.

This behavior is only on interactive shell. When running script, '_'
is not used and Python
may acts you expect.


On Mon, Apr 18, 2011 at 9:56 AM, Charles Solar <charlessolar at gmail.com> wrote:
> I have a python module written in C++, and the C++ code has a few instances
> that involve method chaining.  I was experimenting with python support for
> these methods and I found something odd.
> However it seems this is more a python eccentricity than Boost Python,
> consider the following code sample.
>
> class Test():
>     def __init__( self ):
>             print "Init"
>     def __del__( self ):
>             print "Del"
>     def foo( self ):
>             print "Foo"
>             return self
>     def bar( self ):
>             print "Bar"
>             return self
>
> And some sample uses:
>
>>> Test().foo().bar()
> Init
> Foo
> Bar
> <__main__.Test instance at 0x2aef40e33998>
>>>
>
> Note that __del__ was never called, the object still exists somewhere..
> There is another odd thing though, if I repeat the same line, the previous
> version gets destroyed and replaced by the new version, but only after the
> chain methods are done, eg:
>
>>>> Test().foo().bar()
> Init
> Foo
> Bar
> Del                      <-- Old one, NOT the current instance
> <__main__.Test instance at 0x2b72bc78d998>
>>>
>
> However if I do:
>
> def Tester():
>     Test().foo().bar()
>     # To make sure del is not called by the function returning
>     while True:
>             pass
>
>>> Tester()
> Init
> Foo
> Bar
> Del
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 4, in Tester
> KeyboardInterrupt
>>>
>
> That time __del__ was called immediately ( as intended ).
>
> Is there something I should be aware of here?  Some sort of difference
> between the global instances and ones defined in a function?  Can I do
> anything so global instances are cleaned up immediately like they are inside
> functions?
>
> Thanks
>
>
>
> _______________________________________________
> Cplusplus-sig mailing list
> Cplusplus-sig at python.org
> http://mail.python.org/mailman/listinfo/cplusplus-sig
>



-- 
INADA Naoki  <songofacandy at gmail.com>


More information about the Cplusplus-sig mailing list