which is best for a singleton, module or class?

Hung Jung Lu hungjunglu at yahoo.com
Thu Nov 29 12:32:06 EST 2001


Peter Bismuti wrote:
> What is best for a singleton, making it a module or a class within a module?
> I guess the reason why having a class within a module undesirable is that it
> adds to the namespace of the object mymodule.mclass.property instead of
> mymodule.property, and so fourth.  I know you can import it in a way to
> reduce the path length of the object, but still, it seems like a cleaner
> coding style to just use the module itself.   Opinions? THanks.

You can simply put your object into the __builtins__ namespace:

#---------------------------------------
class Spam:
    x = 0
    def f(self):
        print self.x

__builtins__.__dict__['eggs'] = Spam()

eggs.x = 1
eggs.f()
#---------------------------------------

Using modules is fine for singletons, but classes allows you things
like inheritance.

regards,

Hung Jung



More information about the Python-list mailing list