destructor not called

Bruno Desthuilliers bdesth.quelquechose at
Mon Sep 29 18:39:45 CEST 2008

Marcin201 a écrit :
>> Others have already replied to your main question; in short you
>> shouldn't rely on __del__ being called. Regardless, is there a (good)
>> reason for having an instance reference to the method ? Without
>> further information, that seems like a code smell.
> I have dictionary of fxns to do import/export based on the type of
> request from user so I can call self.Import['html'] or
> self.Import['text'].

getattr(obj, name) is your friend. And if you really want to maintain 
your own mapppings, do it at the appropriate level - that is, when it 
comes to methods, at the class level, not the instance level. You can 
even automate this using a decorator and a custom metaclass, ie 
(warning: Q&D code, not tested, may contain errors etc):

def request_handler(func):
     func._request_handler = True
     return func

class RequestHandlerType(type):
     def __init__(cls, name, bases, dic):
         handlers = getattr(cls, '_handlers')
         for name, attrib in dic:
             if getattr(attrib, '_request_handler', False):
                 handlers[name] = attrib
         cls._handlers = handlers

class BaseRequestHandler(object):
     __metaclass__ = RequestHandlerType

from myframework impoty request_handler, BaseRequestHandler

class MyHandler(BaseRequestHandler):
     def html(self, *args, **kw):
         # code here

     def text(self, *args, **kw):
         # code here

     def dispatch(self, request):
         format = request.format
             handler = self._handlers[format]
         except KeyError:
             # raise appropriate exception here
             return handler(self,  request)

More information about the Python-list mailing list