views:

360

answers:

3

I am just wondering if there is a super global(like PHP) in python. I have certain variables i want to use throughout my whole project in separate files, classes and functions and i don't want to have to keep declaring it throughout each file.

+10  A: 

In theory yes, you can start spewing crud into __builtin__:

>>> import __builtin__
>>> __builtin__.rubbish= 3
>>> rubbish
3

But, don't do this; it's horrible evilness that will give your applications programming-cancer.

classes and functions and i don't want to have to keep declaring

Put them in modules and ‘import’ them when you need to use them.

I have certain variables i want to use throughout my whole project

If you must have unqualified values, just put them in a file called something like “mypackage/constants.py” then:

from mypackage.constants import *

If they really are ‘variables’ in that you change them during app execution, you need to start encapsulating them in objects.

bobince
+3  A: 

Even if there are, you should not use such a construct EVER. Consider using a borg pattern to hold this kind of stuff.

class Config:
    """
    Borg singlton config object
    """
    __we_are_one = {}
    __myvalue = ""

    def __init__(self):
        #implement the borg patter (we are one)
        self.__dict__ = self.__we_are_one

    def myvalue(self, value=None):
        if value:
           self.__myvalue = value
        return self.__myvalue

conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()

Here we use the borg pattern to create a singlton object. No matter where you use this in the code, the 'myvalue' will be the same, no matter what module or class you instantiate Config in.

Shane C. Mason
-1 for using double underscores. That needlessy invokes name mangling. If you mean private, use a single underscore instead.
nosklo
You are SOOO wrong here. A single underscore (as per the Pep 8 document) is a weak indicato that the value can not be imported in a 'from x import *' and a double underscore makes it class private via name mangling, just as I intended.
Shane C. Mason
For example:>>> class A:... _var1 = "hello"... __var2 = "hello2"... >>> a = A()>>> a._var1'hello'>>> a.__var2Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: A instance has no attribute '__var2'>>>
Shane C. Mason
Obviously, the last comment formatted poorly, so I will just explain:If I have a class, and I want a variable to be class private, I MUST use double underscores to make that happen. A single underscore does NOT make that variable class private.
Shane C. Mason
Your example is broken. Last line prints empty string, because `__init__` always resets self.__myvalue.
Constantin
OK, I corrected the error, thanks for the heads up!
Shane C. Mason
+2  A: 

Create empty superglobal.py module.
In your files do:

import superglobal
superglobal.whatever = loacalWhatever
other = superglobal.other
vartec