Welcome, guest | Sign In | My Account | Store | Cart

Sometimes you like to have a very global namespace where to put e.g. configuration data. This data should be accessible form all modules you use. SuperGlobal solves this need.

Python, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import __main__

class SuperGlobal:

    def __getattr__(self, name):
        return __main__.__dict__.get(name, None)
        
    def __setattr__(self, name, value):
        __main__.__dict__[name] = value
        
    def __delattr__(self, name):
        if __main__.__dict__.has_key(name):
            del  __main__.__dict__[name]

superglobal1 = SuperGlobal()
superglobal1.test = 1
print superglobal1.test
superglobal2 = SuperGlobal()
print superglobal2.test
del superglobal2.test
print superglobal1.test
print superglobal2.test

The __main__ module gives you access to the namespace of the main module. Here we just add new objects. Just make an instance of SuperGlobal() and then you have access to this global namespace by setting or getting attributes of this object.

This is a dirty hack, so just use it when you really need it.