On Sun, 27 May 2007 23:20:49 -0700, Jack wrote: > Thanks Steven, for the reply. Very helpful. I've got a lot to learn in > Python :) > > Some questions: > >> (1) Python can automatically free most data structures and close open >> files, but if your needs are more sophisticated, this approach may not be >> suitable. > > Since it's a wrapper of a DLL or .so file, I actually need to call > mylib_exit() > to do whatever cleanup the library needs to do.
Well, there may be better ways, but I'd do something like this: # === mylib module === # Exception raised if library is not initiated class Uninitiated(Exception): pass def _init(): """Private set-up code.""" global DATA, _INITIALIZED DATA = range(100000) # or something more useful _INITIALIZED = True def _close(): """Private tear-down code.""" global DATA, _INITIALIZED del DATA, _INITIALIZED def isinited(): """Return True if the library is initialized, otherwise False.""" try: _INITIALIZED; return True except NameError: return False def init(): """Public set-up code.""" if not isinited(): _init() def close(): """Public tear-down code.""" if isinited(): _close() exit = close # alias for exit/close. def func(): if isinited(): return DATA[0] else: raise Uninitiated("Library is not initialized") All of the above can be modified to be in a class instead of a module. That's especially useful if you can have multiple instances, perhaps with different state. >>> 2. what's the right way to call mylib_exit()? I put it in __del__(self) >>> but it is not being called in my simple test. >> >> instance.__del__ is only called when there are no references to the >> instance. > > I didn't call del explicitly. I'm expecting Python to call it when > the program exits. I put a logging line in __del__() but I never > see that line printed. It seems that __del__() is not being called > even when the program exits. Any idea why? Python tries really really hard to call instance.__del__() but there are pathological cases where it just can't. Maybe you've found one of them. But I'm guessing that you may have defined a __del__ method, but not actually created an instance. If so, __del__ will never be called. This should work: class Foo(object): def __del__(self): print "All gone now" instance = Foo() When you exit, instance will be garbage collected and instance.__del__() will be called. But without the instance, __del__ is not called on the class directly. Hope this was some help, -- Steven. -- http://mail.python.org/mailman/listinfo/python-list