Click to See Complete Forum and Search --> : constants in python


bdg1983
08-17-2001, 02:06 PM
is there a way to declare constants in python (equivelant to c++ "const int fish=5")?

thanks

EscapeCharacter
08-17-2001, 03:12 PM
i would also like to know this...
jemfinch?

EscapeCharacter
08-17-2001, 03:53 PM
found this on the mailing list so i guess you just cant

>3. const variables
> e.g. const int NOCHAGE=1;

Mediocre idea in C++. Not possible in Python, because in Python variables
aren't supposed to be typed in any way -- instead, they hold things which
are typed.

EscapeCharacter
08-17-2001, 04:04 PM
ok i spoke too soon, more from the mailing list
In proper C++, your const will be contained inside a class (probably
static) to keep it out of the global namespace. In proper Python, your
const will also be contained inside a class -- and __setattr__ will be
redefined to disallow changing any values.

class __myConsts:
NOCHAGE = 1
SOMECHAGE = 2

# now make sure nobody can hack my values...
def __setattrs__(self,attrname,value):
raise "can't modify my constants!"

consts = __myConsts()

Now, after you import this module, you can access all your constants
through expressions such as consts.NOCHAGE, but you can't change them.

Well, not quite. It turns out that you CAN change them, but only like
this:

__myConsts.NOCHAGE = 2

...and that only works from within the same file (because names beginning
with underscores are private), so it's probably what you wanted anyhow
(more like Java's 'final' keyword).

so i guess it can be done, that just kinda nasty how it does it though

jemfinch
08-17-2001, 11:07 PM
Other than changing the __setattr__ of a class or writing a C extension type, you can't have constants in Python.

Jeremy