Constants [was Re: newb question about @property]
Steve D'Aprano
steve+python at pearwood.info
Wed Oct 4 11:08:06 EDT 2017
On Thu, 5 Oct 2017 12:41 am, Ian Kelly wrote:
> Python has the simplest named constants of all:
>
> C = 12345
>
> As long as you don't subsequently change it, it's a constant. And it's
> very simple because it works just like any other variable.
I do feel that the lack of constants[1] is a (mild) weakness of Python. In
small projects, if you want a constant:
pi = 3.1415
and you don't want to change it, it is easy enough to remember to just not
change it. Especially if you follow a naming convention like using ALLCAPS
for constants.
But in large projects, especially those where you cannot trust every module in
the project to obey the naming convention, I can see that this lack might
contribute to the perception, if not the fact, of Python being a bit too
unsafe for big projects. We have read-only attributes in classes, but not
read-only names in modules. That makes me a little bit sad.
Back in the day when I used Pascal regularly, I recall having the compiler
complain when I accidentally tried to assign a new value to a constant. But I
was a much less experienced coder back then. In all honesty, I can't remember
the last time I accidentally reassigned to something intended as a constant.
Nevertheless, constants are a safety net I would appreciate.
[1] By which I mean names which can only be bound once, but not rebound. This
is not about mutability, it is about whether or not the name can be rebound.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list