[Tutor] What are "singletons" good for?

Knacktus knacktus at googlemail.com
Sat Sep 18 18:50:42 CEST 2010


Hey all,

the usual explanation for the usage of a Singleton goes like this:

"Use a singleton if you want to make sure, that only one instance of a 
class exists."

But now I ask myself: Why should I call the constructor of a class more 
than once if I only want one instance?
After all, I decide in my code when to create an instance or when to 
pass an existing instance around.

Example in pseudocode:

class Session(object):
     """Hold a dictionary of ident_to_data_objects"""

     def __init__(self, ident_to_data):
         self.ident_to_data = ident_to_data

Now, that would be a typical "singleton" use case. I want one instance 
of this class application-wide. For example in a View class:

class View(object):
     """Create fancy views"""

     def __init__(self, session):
         self.session = session

In my code I use these classes like this:

class MainApp(object):
     """Do some stuff with the data_objects"""

     def __init__(self):
         self.session = Session()
         self.view = View(self.session)

Would a singleton usage in the View class look like that?

class View(object):
     """Create fancy views"""

     def __init__(self):
         self.session = Session()

What's the point? Is it the spared typing when instanciating a lot of 
View classes (I wouldn't need to pass the session to the constructor). 
Or are there some more advantages (instead of passing the same instance 
aorund)? Also, what would you guys consider as disadvantages?


Another question related to this topic is, if I would use a module as a 
singleton (as suggested by Steve and other), how would I import it the 
instances of a class? Maybe like this?

class View(object):
     """Create fancy views"""

     import session

     def do_something(self, ident):
         self.certain_data_object = session.ident_to_data[ident]

A lot of questions, so thanks in advance for any comments!

Cheers,

Jan


More information about the Tutor mailing list