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

Remy Blank remy.blank_asps at pobox.com
Tue Dec 7 16:50:27 CET 2004

Philippe C. Martin wrote:
> I have a very large XML file that I load into dictionnaries defined in a class 
> located in a module that is imported in many places.
> Since the loading process is very slow, I would like the file not to be loaded 
> on import or class instantiation, but only once (on first import or class 
> instantiation).

What about:

class MyClass:
    hugeDict = loadHugeDic("filename.xml")

    def __init__(self):
        """hugeDict can be accessed by self.hugeDict"""

The function loadHugeDict() will only be called once, when importing the
module for the first time. If you wanted to load it on the first
*instantiation*, you could do:

class MyClass:
    hugeDict = None

    def __init__(self):
	if MyClass.hugeDict is None:
            MyClass.hugeDict = loadHugeDic("filename.xml")

-- Remy

Remove underscore and suffix in reply address for a timely response.

More information about the Python-list mailing list