How do you create constants?

Alex Martelli aleaxit at yahoo.com
Thu Nov 2 05:17:54 EST 2000


"Quinn Dunkan" <quinn at retch.ugcs.caltech.edu> wrote in message
news:slrn901u6m.m0t.quinn at retch.ugcs.caltech.edu...
> On Tue, 31 Oct 2000 11:10:25 +0100, Alex Martelli <aleaxit at yahoo.com>
wrote:
> >"Mikael Olofsson" <mikael at isy.liu.se> wrote in message
> >news:XFMail.001031081500.mikael at isy.liu.se...
> >> Can someone tell me why anyone would need true constants?
> >
> >To give a "readable name", emphasizing their meaning,
> >to what one could otherwise express in code as (e.g.) a
> >number.
>
> You didn't answer his question.  I believe his question was "Can't you
just
> bind a name and then not rebind it?  If it's easy to just not rebind
names,
> why do we need a special language construct?"

His question was the one we're quoting.  If he meant
to ask different questions, he can probably phrase
them himself, rather than requiring an interpreter:-).

The questions you're expressing are rather in the
nature of _objections_ to the answer I did give (to
the literal question he had posed).


> You answer sounded like: "So you can bind a name, and not worry about it
> getting accidentally clobbered."

This is the gist of it, yes.  The usefulness of constants
is being able to use names rather than literals without
introducing any exposures.

> The real question is "what do you mean by 'accidentally clobber'?"  I
believe
> he was looking for ways you accidentally type 'math.pi = 3'.  I'm
interested
> in those ways, too, since I can't think of any.  But maybe they're there
on
> certain kinds of projects.

If you're willing to use a structured-name (of the foo.bar
kind) rather than a bare-name (just an identifier), you can
indeed feel rather safe that it won't get accidentally
re-bound (as long as you establish and enforce a convention
that no module re-binds fields in another module).  Accidental
re-binding risk mostly affects bare-names.

With a structured-name, you can also make _sure_ it will
not be accidentally re-bound (by using as the left part
a UserDict which enforces "no rebinding of keys without
'proper procedure').  The risk is on the top-part, the
leftmost bare-name in the structured-name, basically.

Accordingly, the risk is highest for modules designed
to be used with "from foo import *" (e.g., wxPython),
and modules that inject 'built-ins' (e.g., mxTools).


Alex






More information about the Python-list mailing list