PEP 8 prescribes that
Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include
MAX_OVERFLOW
andTOTAL
.
I understand that this is a naming convention only, but I'm curious to know if there is an official or widely-accepted definition of what actually constitutes a constant versus a semi-private variable.
Is this limited to what you might call mathematical constants? (Namely float, int, complex)
Or would it include things like datetime.date
objects or strings that are defined at the module level? How about a dictionary with keys/values of mixed types? If the answer is no, should these types of objects be defined like (quasi-) private variables with _leading_underscore
?
Well, the PEP 8 coding conventions were primarily written for the Python standard library:
Grepping through some of the modules in the Python 3.5 standard library, alongside with the usual strings and numbers, one finds things like
UUID
s, uuid.py:regular expressions, smtplib.py
dictionaries, plistlib.py:
frozenset
s, asyncore.py:and a
datetime.date
in calendar.pythus basically anything that is supposed to remain constant for the entire duration of the execution, even if it were a mutable type (the dictionary in plistlib.py).
For the most part in python the PEP8 naming convention for constants is just there to help any programers who are reading the code know not to change that particular "constant" In other languages like C it actually can reduce the time it takes to execute code.
See this post on The Benefits of Constants
A constant is just a value that never changes.
In OOP it is useful to declare private or public constants but for python there is no functional separation from "Constants" and regular variables.
One more thing in other programming languages that support true constants if you declare a value as a constant then that value cannot change not even if you try to reassign that value later. In python however there are no constants so we use the naming convention to help us remember not to change that value.