Assigning to self

Jeff Shannon jeff at ccvcorp.com
Tue Jan 18 18:52:41 EST 2005


Marc 'BlackJack' Rintsch wrote:

> Frans Englich wrote:
> 
>>Then I have some vague, general questions which perhaps someone can reason 
>>from: what is then the preferred methods for solving problems which requires 
>>Singletons?
> 
> As already mentioned it's similar to a global variable.  If I need a
> "Singleton" I just put it as global into a module.  Either initialize it
> at module level or define a function with the content of your __init__().

If one is determined to both use a Singleton and avoid having a plain 
module-global variable, one could (ab)use function default parameters:

class __Foo:
     "I am a singleton!"
     pass

def Foo(foo_obj = __Foo()):
     assert isinstance(foo_obj, __Foo
     return foo_obj

Of course, this suffers from the weakness that one might pass an 
object as an argument to the factory function and thus temporarily 
override the Singleton-ness of __Foo... but a determined programmer 
will work around any sort of protection scheme anyhow. ;)

In general, ISTM that if one wants a Singleton, it's best to create it 
via a factory function (even if that function then masquerades as a 
class).  This gives you pretty good control over the circumstances in 
which your Singleton will be created and/or retrieved, and it also 
makes it trivial to replace the Singleton with some other pattern 
(such as, e.g., a Flyweight or Borg object) should the need to 
refactor arise.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list