singletons

Carl Banks pavlovevidence at gmail.com
Thu Jul 17 02:46:36 EDT 2008


On Jul 16, 6:20 pm, Craig Allen <callen... at gmail.com> wrote:
> Anyone have any comments?  Is there anything wrong, evil, or ugly
> about using a module this way, or am I correct to think that actually,
> this is a common approach in python.
>
> Is it pythonic?


The one drawback to this is that it could require lots of globals
definitions.  Whereas in a regular class you could do this:

def something(self):
    self.var = 1
    self.max = 10

using a module as a singleton you'd be doing this:

def something():
    global var
    global max
    var = 1
    max = 10


If you have a lot of "attributes" of your module to redefine, I'd
suggest taking steps to avoid globals.  The most straightforward way
is to define a self variable in your module that is bound to the
module itself, and access all "attributes" through that.  The
following code should suffice (though it may not work in some corner
cases):

self = sys.modules[__name__]

So then you could rewrite the something method like so:

def something():
    self.var = 1
    self.max = 10


[Another possibility, and this is what I do, is to use a function
decorator that passes the module in as the first argument.  I have
reasons for doing it but it doesn't do anything the above method
does.  It would be used like this:

@modmethod
def something(self):
    self.var = 1
    self.max = 10

]


Carl Banks



More information about the Python-list mailing list