Defining/declaring constants in Python
Irmen de Jong
irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Mon Jul 28 13:58:17 EDT 2003
Sriram Chadalavada wrote:
> I am currently using raw numerical values and was wondering if
> there is an equivalent of #define in Python for declaring constants.
> Is there an elegant way of defining constants in Python? Please let
> me know.
First, #define is not declaring constants in C or C++.
It is a preprocessor instruction that tells the compiler to replace
a piece of source code text by another piece.
That aside,
there is no such thing as a preprocessor or constant declarations in Python.
You can just define a bunch of attributes. That's what I do usually,
for example in the constants.py module of my Pyro project:
RIF_Varargs = (1<<0)
RIF_Keywords = (1<<1)
RIF_Oneway = (1<<2)
RIF_VarargsAndKeywords = RIF_Varargs | RIF_Keywords
DENIED_UNSPECIFIED=0
DENIED_SERVERTOOBUSY=1
DENIED_HOSTBLOCKED=2
DENIED_SECURITY=3
...and so on.
If you need 'constants' in a stricter sense, have a look at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207
--Irmen
More information about the Python-list
mailing list