Python Global Constant
Peter Hansen
peter at engcorp.com
Wed Jul 9 09:15:00 EDT 2003
Christoph Becker-Freyseng wrote:
>
> >>*** module any ***
> >>import dirs;
> >>def CheckDir(Dir):
> >> if Dir=dirs.Const_Up: xxx
> >
> >
> > This code should work fine, although you might want to follow
> > the Python conventions ........
>
> What about using __builtins__ wouldn't make this the constant really global?
A module is already global, in the sense that if you do "import xxx"
you will get a reference to a singleton module object (generally from
xxx.py), which provides a nice clean namespace for a set of names such
as constants.
This makes it easy for someone reading the code to see where a constant
is defined, and it provides a necessary level of organization.
Putting something in __builtins__ is not only stylistically a bad
idea for most things, but it also hides the source of the name and
anyone reading the file will be at a loss to figure out where it
came from unless every reference to it is preceded by a big comment::
# WARNING! The author of this code chose the silly approach
# of storing a reference to this constant in the __builtins__
# namespace, which is why you can't find where it is defined.
# This reference was stored in the initialization code that
# is in init.py, and instead of just leaving the name there
# so you could call it "init.CONSTANT", it was slipped in
# through the back door to let the author save five keystrokes,
# at the expense of readability, but with this comment everything
# will be okay.
x = CONSTANT
How is that better than using the proper approach of storing constants
in a module, such as "constant.py"? ;-)
-Peter
More information about the Python-list
mailing list