Factory pattern implementation in Python

Gabriel Genellina gagsl-py at yahoo.com.ar
Mon Dec 4 18:39:31 EST 2006


At Monday 4/12/2006 13:39, googlegroups at romulo.e4ward.com wrote:

>class Factory:
>   def __isValidEventClass(self, obj):
>     if inspect.isclass(obj) and obj != events.EvtBase and \
>         events.EvtBase in inspect.getmro(obj):
>       for m in inspect.getmembers(obj):
>         if m[0] == 'eventNum':
>           return True
>     return False
>
>   def __init__(self):
>     self.__eventDict = {}
>     for m in inspect.getmembers(events, self.__isValidEventClass):
>       cls = m[1]
>       self.__eventDict.update({cls.eventNum: cls})
>
>   def parseEvents(self, file):
>     while not file.eof():
>       ev = file.read(1)
>       self.__eventDict[ev](file).execute()

You already got other ways to go.
But if you want to use several classes (maybe span along several 
modules), you can code the checking a lot more easily:

if issubclass(cls, EvtBase) and hasattr(cls, 'eventNum'): ...

I'd register each class itself, so no need to iterate over the 
members, but anyway you could use vars(module).
In short, inspect may be good for debugging or documenting tools, but 
hardly needed for usual code.

BTW, that file format is horrible. Users have to know *every* posible 
event (at least its size), even if the're not interested in them. And 
if you get out of sync, you can't recover. Add a new event, and all 
programs using the file don't work anymore. Ugh!


-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list