[Tutor] quick query relating to globals (I think)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 24 Jun 2002 10:09:36 -0700 (PDT)


On Mon, 24 Jun 2002 alan.gauld@bt.com wrote:

> > >   Hmm...just a sec, if thing.py initialised it's own instance of
> > > thing, at the global level, then could one.py and two.py do an
> > > 'import thing' and access it with thing.thing?
> >
> > ...modules are cached and loaded only once, we're guaranteed that that
> > instance will be instantiated only once.
>
> Oops, I'd forgotten about that little feature. So yes you could do this.
> Its still a really bad idea to have code in one module dependant on the
> existence of an instance in another module however.


In that case, then this 'singleton.py' module could have a factory
function that returns the instance itself:

###
## singleton.py

import time
class TimedObject:
    def __init__(self):
        self.instantiation_time = time.time()
    def __str__(self):
        t = time.localtime(self.instantiation_time)
        return "I was instantiated at %s" % \
            time.strftime("%I %M %p", t)

_singleInstance = TimedObject()

def grabSingleton():
    """A factory object that returns the singleton object."""
    return _singleInstance
###

This is nicer because all access to our "single" object is handled through
a grabSingleton() function.  Rather than rudely pulling the singleton out
of the module, we can now use grabSingleton() to nicely ask the module to
give us our instance.


Hope this helps!