Constants and Globals

Erik Max Francis max at alcyone.com
Sat Dec 14 16:29:51 EST 2002


Travis Beaty wrote:

> 1.  Is there such an animal as a "constant" in Python?  I've looked
> through the manual, documentation, and FAQ's, but I haven't been able
> to
> find an answer about that.  I'm sure it's there somewhere, and I've
> just
> overlooked it.  I noted that the term "constant" was used, but I am
> unsure whether one can actually lock the value of a variable, or
> whether
> such constants are simply "constant by agreement."

There's really no way to make something _truly_ const without trickery
(you could, for instance, create an object whose attributes acted as if
they were constant by preventing you from modifying them, at least if
they only contained immutable objects).  Python takes the approach of
"We're all adults here"; instead of trying to enforce things that can be
hard to enforce in the language (usually there's ways around const
correctness in other languages, even if they result in undefined
behavior), Python doesn't even try.

Most of these "hints" are done by convention, rather than by syntax. 
The common approach to indicate a constant in Python is to have an
ALL_CAPS_IDENTIFIER (which, of course, isn't specific to Python).

> 2.  I'm working on an application that needs to have a global
> variable.
>  I, of course, do my best to shy away from globals; however, since
> this
> is a dictionary which contains user preference settings, I can see no
> other alternative.  I've implemented this global variable by placing
> it
> into a module which will be imported by all other modules.  Is this
> the
> "standard" way that globals are created?  Again, I've read the docs
> and
> tutorial where variable scope is concerned, but I'm still a little
> unclear on it.

Your global could be at the top level of _any_ module, as long as the
others import it.  Putting it in its own module is a good way to avoid
hairy issues (one which most Python newbies have come across and been
confused by), where you have recursive imports.  If the global is in its
own dedicated module, this definitely lightens the load and eliminates
the recursive imports problem.

So the short answer is that it may be overkill -- it could really be in
_any_ module -- but if you have a complex system of modules, it's a good
way to ensure that you eliminate any kind of import ordering or
recursing problems.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ A physicist is an atom's way of knowing about atoms.
\__/ George Wald
    Python chess module / http://www.alcyone.com/pyos/chess/
 A chess game adjudicator in Python.



More information about the Python-list mailing list