On 08/11/2015 02:59, Steven D'Aprano wrote:
On Sun, 8 Nov 2015 02:01 am, Bartc wrote:
Neither have the simplicity of concept of Pascal's 'const', which is
just a named value. Not a variable that won't change once initialised,
not a parameter that won't be changed nor any addressable location.)
Unfortunately the concept of "named value" doesn't match well with Python's
design. That implies a separate compilation step which doesn't fit well
with Python's runtime semantics. Very little happens at compile-time in
Python that *must* happen at compile-time.
I'm also not sure what difference you think there is between "named value"
and "variable that won't change once initialised".
This is what I mean about people not understanding it!
In NASM terms, a named constant is like:
daysinweek equ 7 ; definition
mov rax, daysinweek ; using it, as immediate value
mov rbx, daysinweek*2 ; an a 'compile-term' expression
; mov daysinweek,8 ; can't be done! Illegal syntax
While a 'const' variable, C style, might be:
segment .rodata
monthsinyear: ; definition
dd 12
mov rax,[monthsinyear] ; using it, as memory access
; mov rbx,[monthsinyear*10] ; can't be done!
mov [monthsinyear],6 ; can be done, but might give memory
; access errors if actually stored in
; protected memory. Usually in C,
; it isn't
So in native code, a named value is not much different to a literal such
as 7, or 3.14159. (But unlike C's #define, the name is a proper symbol
with normal scope rules, and a type).
The distinction at the machine level can be blurred with some
instructions sets where there might not be an immediate data option for
some data widths or types. Also where named constants are applied to
things such as strings, which necessarily use storage.
In the language however, you will not be able to use the named constant
as an lvalue, and you will usually be able to use it for compile-time
constant folding and for dimensioning fixed-bound arrays and such.)
Python has a convention for "constants" -- all UPPERCASE names. The fact
that the convention exists is enough to prove that the concept
of "constant" is a useful one. The difference between Python's
pseudo-constants and (say) Pascal's actual constants is that in Python, the
burden of ensuring that neither you, nor any of the libraries you call,
modifies the "constant" falls on you, the user, whereas in Pascal the
compiler or interpreter performs that checking for you.
With a real named constant the check can always be done at compile-time.
Unless you have a pure interpreter or some more elaborate way of
executing source code.
(In the case of Python, the main obstacle is that a constant name from
inside an imported module is not visible when this module is compiled to
byte-code. So it has to assume it can be anything.)
--
BartC
--
https://mail.python.org/mailman/listinfo/python-list