Defining constant strings

Tal Einat tal.no.no.spam at gmail.com
Sun Aug 27 12:17:16 EDT 2006


Hans wrote:
> Hi,
>
> I want to define a couple of constant strings, like in C:
> #define mystring "This is my string"
> or using a const char construction.
>
> Is this really not possible in Python?
>
> Hans

It is really not possible.

The Pythonic way (as far as I have come to know it) is to stop trying
to protect yourself from yourself, and just don't change something
which should be constant. Good documentation (including in-code
comments) and good design are better for preventing programming errors
than defining things as constant.

Actually, you can't really define anything as constant in C either. A
#define can be overriden, a 'const' variable can be casted. These are
merely conventions which are enforced to some degree by compilers, but
can easily be worked around.

There are conventions for constant values in Python too. Usually,
variables with an all uppercase name are used. As for variables,
functions, attributes, methods etc. which shouldn't be changed/used
outside a certain module/class: these are usually prefixed with an
underscore ("_"). These are not enforced by the interpreter at all,
though.


As a side note, Python strings are actually all constants, or
"immutable" in Python-ish. The variables which reference string objects
can be changed to reference any other object - that's the nature of
Python variables. But the strings themselves don't change.

- Tal




More information about the Python-list mailing list