How do I make a constant global variable in Python Please

Christian Tismer tismer at tismer.com
Mon Apr 17 13:38:57 EDT 2000


Hi,

cmfinlay at magnet.com.au wrote:
> 
> How do I make a constant global variable in Python Please.
> or just a constant.
> or just a global.
> 
> I bought a Python Book. however I can't find this info in it.
> 
> Please e-mail me at cmfinlay at magnet.com.au
> --
> http://www.python.org/mailman/listinfo/python-list

There is no such concept as you required, but it can be modelled.
If you can live with the rule that you need to use one global
thunk that holds your real vars/consts, then the following will
work for you.

The advantage of this approach:
After the debugging phase, you can replace the "declared" class
with an empty class, and things will work just faster.
You can also use it to monitor usage of certain variables
if you like.

ciao - chris

file declared.py
--------------------------------------------------------------------
# declared global variables
# done with a class.
#
# Christian Tismer, Y2k0417

class declared:
    """A class that mimicks declaration of variables before use.
    Usage example:
        g = declared("hi there")
    gives you write access to the attributes "hi" and "there".
    Note that they cannot be read before they have been set.
    """
    def __init__(self, namestring=""):
        self.__dict__["__names__"] = {}
        self.declare(namestring)
    def __setattr__(self, key, value):
        dic = self.__dict__
        nam = dic["__names__"]
        dic[nam[key]] = value

    def __getattr__(self, key):
        dic = self.__dict__
        nam = dic["__names__"]
        return dic[nam[key]]

    def vars(self):
        return self.__names__.keys()

    def declare(self, namestring):
        import string
        for name in string.split(namestring):
            self.__names__[name] = name

sample_session = """
>>> g=declared("hi there")
>>> g.vars()
['hi', 'there']
>>> g.hi
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
  File "D:\python\spc\declared.py", line 24, in __getattr__
    return dic[nam[key]]
KeyError: hi
>>> g.hi=4
>>> g.hi
4
>>> del g.hi
>>> g.hi
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
  File "D:\python\spc\declared.py", line 24, in __getattr__
    return dic[nam[key]]
KeyError: hi
>>>
"""
------------------------------------------------------------------

-- 
Christian Tismer             :^)   <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaunstr. 26                  :    *Starship* http://starship.python.net
14163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     where do you want to jump today?   http://www.stackless.com




More information about the Python-list mailing list