Python – how do I write a "getter" function that will return a variable stored in my module (initiating it first if needed)?

Question:

Here is the complete code of my module, called util.py:

import my_other_module

__IMPORTANT_OBJECT__ = None

def getImportantObject():
    if __IMPORTANT_OBJECT__ is None:
        __IMPORTANT_OBJECT__ = my_other_module.ImportantObject()
    return __IMPORTANT_OBJECT__

My understanding is that variables prefixed with a double underscore are considered private to a module. The idea here is that I would like to store a private reference to the important object and the return it to anyone who asks for it via the getImportantObject() method. But I don’t want the object to be initiated until the first time this method is called.

When I run my code, however, I get the following error:

File "/Users/Jon/dev/util.py", line 6, in getImportantObject
    if __IMPORTANT_OBJECT__ is None:
UnboundLocalError: local variable '__IMPORTANT_OBJECT__' referenced before assignment

What is the recommended way to accomplish what I am trying to do here?

Asked By: tadasajon

||

Answers:

The variable is not considered private; rather it’s seen as a local variable.

Use the global keyword to mark it as such:

def getImportantObject():
    global __IMPORTANT_OBJECT__
    if __IMPORTANT_OBJECT__ is None:
        __IMPORTANT_OBJECT__ = my_other_module.ImportantObject()
    return __IMPORTANT_OBJECT__
Answered By: Martijn Pieters
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.