Python Global Constant

Michael Chermside mcherm at
Wed Jul 9 14:48:25 CEST 2003

Krisztian Kepes wrote:
> How [do] I create an global constant in [a] module [that] is 
> accessable in from other modules ?

Christoph Becker-Freyseng replies:
> What about using __builtins__ wouldn't make this the constant 
> really global?

While adding it to __builtins__ *would* work like you're thinking,
it's not necessary, or appropriate. Python provides lots of ways
for "power users" to "get under the covers" and change things.
This is useful in those situations where you really need it (some
other languages provide NO way to get at fundamental language
features), but such deep black magic should be reserved for those
cases when you really need it. Modifying __builtins__ definitely
falls into such a category: if you aren't sure whether you need
to do it, then you don't. If you *think* you need to do it, then
you shouldn't. If you understand what's going on so well that you
are *certain* that you *must* modify it to achieve what you want...
well, go ahead!

In this case, the OP (original poster) was asking about a very
common and straightforward situation: module level constants that
need to be visible from other modules. There is a standard and
straightforward way to create these: just assign a value to the
variable in your module, then use it from other modules by
importing the module. Spell the variable with ALL_CAPS to clearly
mark that it is intended to be a constant and others shouldn't
modify it. You'll need to watch out for cyclic import dependencies,
but other than that this is a really easy solution.

Now, some might complain that the variable isn't "constant"...
spelling it with all caps tells others that they SHOULDN'T modify
it, but doesn't PREVENT them from doing so. Really, that's a lot
like the issue with __builtins__ that I mentioned above. It's very
Pythonic to have a clear *indication* that something shouldn't be
messed with (being in all caps or marking with double underscore),
but not to *enforce* it -- if someone wants to change it they do
so at their own risk. However, if you REALLY wanted to keep them
from changing the "constant" (perhaps it controls the security
level for running untrusted code) there are ways to do so -- check
out the Python Cookbook for some examples.

-- Michael Chermside

This mail sent through IMP:

More information about the Python-list mailing list