Julius B. Lucks/Projects/Python Articles/Design Patterns In Scientific Programming

This is not an article, but a scratch pad that will eventually be massaged into an article.

= Patterns in Python =

Singleton
See Jeff Pitman's solution in the comment section in the Python Cookbook. Test code looks like

class Singleton(object): """The Singleton Class Definition" def __new__(cls,*p,**k): if not '_the_instance' in cls.__dict__: cls._the_instance = object.__new__(cls) return cls._the_instance

s = Singleton t = Singleton q = Singleton
 * 1) Create 3 instances of Singleton

print s print t print q
 * 1) Note that you can see that they are the same
 * 2) object by the hex id of the objects

id(s) == id(t) == id(q)
 * 1) You can also see that since they have the
 * 2) same id's

class SingletonChild(Singleton): """Inherited from the Singleton class.""" pass
 * 1) Now try an inheritance example

w = SingletonChild m = SingletonChild

id(w) == id(m)
 * 1) Note w and m are the same

id(w) == id(s)
 * 1) But w and s are different

Chain of Responsibility

 * Very useful for handling dependincies in inputs for pipeline code
 * See Design Patterns in Python

class Event: def __init__( self, name ): self.name = name

class Widget: def __init__( self, parent = None ): self.__parent = parent def Handle( self, event ): handler = 'Handle_' + event.name if hasattr( self, handler ): method = getattr( self, handler ) method( event ) elif self.__parent: self.__parent.Handle( event ) elif hasattr( self, 'HandleDefault' ): self.HandleDefault( event )