<s> referents = [ ] <EOL> freelist = None <EOL> def store ( x ) : <EOL> "<STR_LIT>" <EOL> global freelist <EOL> p = freelist <EOL> if p is None : <EOL> p = len ( referents ) <EOL> referents . append ( x ) <EOL> else : <EOL> freelist = referents [ p ] <EOL> referents [ p ] = x <EOL> return p <EOL> def discard ( p ) : <EOL> """<STR_LIT>""" <EOL> global freelist <EOL> x = referents [ p ] <EOL> referents [ p ] = freelist <EOL> freelist = p <EOL> return x <EOL> class Ref ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , x ) : <EOL> self . x = x <EOL> def __enter__ ( self ) : <EOL> self . p = p = store ( self . x ) <EOL> return p <EOL> def __exit__ ( self , * args ) : <EOL> discard ( self . p ) <EOL> def count_pyobj_alive ( ) : <EOL> result = len ( referents ) <EOL> p = freelist <EOL> while p is not None : <EOL> assert result > <NUM_LIT:0> <EOL> result -= <NUM_LIT:1> <EOL> p = referents [ p ] <EOL> return result <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> import api <EOL> ffi = api . PythonFFI ( ) <EOL> ffi . cdef ( """<STR_LIT>""" ) <EOL> @ ffi . pyexport ( "<STR_LIT>" ) <EOL> def length ( p_list ) : <EOL> list = referents [ p_list ] <EOL> return len ( list ) <EOL> @ ffi . pyexport ( "<STR_LIT>" ) <EOL> def getitem ( p_list , index ) : <EOL> list = referents [ p_list ] <EOL> return list [ index ] <EOL> @ ffi . pyexport ( "<STR_LIT>" ) <EOL> def pyobj_dup ( p ) : <EOL> return store ( referents [ p ] ) <EOL> @ ffi . pyexport ( "<STR_LIT>" ) <EOL> def pyobj_close ( p ) : <EOL> discard ( p ) <EOL> @ ffi . pyexport ( "<STR_LIT>" ) <EOL> def pyobj_getitem ( p_list , index ) : <EOL> list = referents [ p_list ] <EOL> return store ( list [ index ] ) <EOL> @ ffi . pyexport ( "<STR_LIT>" ) <EOL> def pyobj_add ( p1 , p2 ) : <EOL> return store ( referents [ p1 ] + referents [ p2 ] ) <EOL> lib = ffi . verify ( """<STR_LIT>""" ) <EOL> with Ref ( [ <NUM_LIT:10> , <NUM_LIT:20> , <NUM_LIT:30> , <NUM_LIT> ] ) as p_list : <EOL> print lib . sum_integers ( p_list ) <EOL> with Ref ( <NUM_LIT:5> ) as p_initial : <EOL> result = discard ( lib . sum_objects ( p_list , p_initial ) ) <EOL> print result <EOL> assert count_pyobj_alive ( ) == <NUM_LIT:0> </s>
