[Edu-sig] Re: Design Pattern question

Dethe Elza dethe.elza at blastradius.com
Tue Oct 21 13:16:02 EDT 2003

Keeping state shared across many instances is what the Singleton 
pattern is commonly used for.  Alex Martelli has a great recipe on the 
Python Cookbook site about how to create instance variables which share 
state, called the Borg pattern[1].  This may be overkill for what 
you're doing, but it offers an interesting perspective.

In the situation you describe I've taken several tactics.  One is to 
have a *single* global object to store preferences or other shared 
state.  Another is to pass the shared state around in one object that 
various parts of the system all have access to.

And the Extreme Programming folks would preach YAGNI (You Ain't Gonna 
Need It).  There is a perception that globals are evil and should never 
be used, but a) python's namespaces already help protect from the worst 
aspects of globals (most 'globals' are really module-local), and b) if 
a program is small or one-off it doesn't make sense to overdesign it 
just to remove globals that won't effect anything.

My first drafts of programs are often littered with globals.  When I 
have a working version and want to add more utility, or reuse bits in 
another program, or find it growing to the point that the globals are 
getting in the way, I refactor them into a single object and use it as 
above.  But only after I find myself returning to the program again and 
again, so that I know the effort will be worth it.


"the city carries such a cargo of pathos and longing
  that daily life there vaccinates us against revelation"
  -- Pain Not Bread, The Rise and Fall of Human Breath

More information about the Edu-sig mailing list