Actually, this is not the recommended approach, and I have never seen it used in real code.
The recommended approach is to use a module as a module already has a "global" namespace (see this answer for more info on globals()
, locals()
, and vars()
).
However, in the interests of understanding:
What you have so far is only a basic framework for shared state at the instance level. What you need now is the rest of the state you want to track:
class Config(Borg):
def __init__(self, config_file):
super(Config, self).__init__()
# load and parse file, saving settings to `self`
One disadvantage to this method is that you can have several instances consuming memory that all know the same thing. (Not much memory, true.)
Another method of accomplishing "shared state" is to only create one instance, and then have the class always return that same instance -- otherwise known as a singleton
.
class Config(object):
the_one = None
def __new__(cls, config):
if cls.the_one is None:
cls.the_one = Super(Config, cls).__new__(cls)
# load and parse file, saving settings to `cls.the_one`
return cls.the_one
Either method would result in the following:
>>> config = Config('my_config_file.cfg')
>>> config.screen_size
# whatever was saved during the loading and parsing of the config file
# for 'screen_size'