Loading a file only once into an object and being able to access it from other modules - still have a problem

Jeff Shannon jeff at ccvcorp.com
Thu Dec 9 22:25:53 CET 2004

Philippe C. Martin wrote:

>After all of you answers, I though I had it straight, yet .....
>This is what  I am doing:
>class SC_ISO_7816:
>    __m_loaded = None
>    def __init__(self):
>        if SC_ISO_7816.__m_loaded == None:
>            SC_ISO_7816.__m_loaded = True
>	    print 'LOADING'
>            self.__Load()
>            print self.SW1_DICT
>        else:
>            print 'DICT ALREADY LOADED!',
>            print self.SW1_DICT
>            pass

I'd take an entirely different approach to creating a Singleton.  I'd 
have it in its own module, and create a private but ordinary class (with 
no special class variables, init tests, or anything).

class __ISO_7816:
    def __init__(self):
        # loading code goes here...
        # ...

Then, I'd create a factory function that ensures that only a single 
instance gets created, and treat that factory function as the only way 
to instantiate the Singleton class:

__my_ISO_obj = None
def SC_ISO_7816():
    global __my_ISO_obj
    if __my_ISO_obj is None:
        __my_ISO_obj = __ISO_7816()
    return __my_ISO_obj

The rest of your code then calls ISO_module.SC_ISO_7816().  The first 
time it's called, an instance of this class is created.  All subsequent 
calls just return a reference to the same instance.  This ensures that 
any changes to the instance are reflected anywhere that the object is 
used.  (In your code, only changes to the class SW1_DICT are reflected 
elsewhere, not changes to any other attributes.)

Jeff Shannon
Credit International

More information about the Python-list mailing list