How do you create constants?

Jan Dries jdries at mail.com
Sat Oct 28 23:04:12 EDT 2000


> 
> "Grant Griffin" <not.this at seebelow.org> wrote in message
> news:39FAF237.87444C5A at seebelow.org...
> > However, unlike most other languages, Python doesn't have scalar
> > constants; if you want those, you'll have to fake them somehow (as
> > others have suggested.)
> 

Here's a piece of code I once put together to simulate constants:

class const:
    def __init__(self,**values):
        self.__mvalues = values
    
    def __getattr__(self,name):
        try:
            return self.__mvalues[name]
        except:
            raise AttributeError
    
    def __setattr__(self,name,value):
        if name == "_const__mvalues":
            self.__dict__[name] = value
        else:
            raise AttributeError

You can then write:

    myconsts = const( pi = 3.1415,  page_size = 4096,  name = "some
name")

and use them like:

    diameter = 2 * radius * myconsts.pi

Assigning to such a constant will raise an AttributeError (at run time
of course; it's still Python)

Regards,
Jan




More information about the Python-list mailing list