Should constants be introduced to Python?
Terry Reedy
tjreedy at udel.edu
Thu Nov 16 17:27:52 EST 2017
On 11/16/2017 4:55 PM, Michael Torrie wrote:
> On 11/15/2017 11:16 PM, Saeed Baig wrote:
>> - Do you guys think it would be a good idea? Why or why not? Do you
>> think there’s a better way to do it? I’d like to know what others
>> think about this idea before making any formal submission.
>
> Except for forcing it to be read-only, there's absolutely no difference
> between your idea of a constant and a normal module name in Python.
> Since Python is a dynamic language, all names have to be looked up at
> run time. So there's really no speed benefit to having a special const
> syntax. In Python, we normally expect developers to act as consenting
> adults. Thus a constant is often denoted by an uppercase name (at least
> in the scripts I've seen), similar to C or other languages. We can just
> say to developers, please don't rebind a name that's all capitals.
> That's it.
The idea of named constants has been proposed before, and rejected
pretty much for the reason you give above.
> Constants as you propose really only make sense in statically-typed,
> compiled languages where the compiler replaces the constant names with
> the values in the compiled code. Doesn't work that way in Python, where
> things are interpreted at run time.
CPython, at least, already has anonymous constant objects. Number and
string literals are turned into objects when parsed. I presume that all
implementations do this. Some constant expressions are replaced by
(constant) objects during compiling, instead of when running. For
instance "n = 10 + 3' will run as 'n = 13', and "for lang in ('C',
'Java', 'Python') will have the tuple pre-computed (whereas "for lang in
['C', 'Java', 'Python] will have to construct the list each time run).
--
Terry Jan Reedy
More information about the Python-list
mailing list