What exactly constitutes a constant in Python?

試著忘記壹切 提交于 2019-12-01 13:37:13

Well, the PEP 8 coding conventions were primarily written for the Python standard library:

This document gives coding conventions for the Python code comprising the standard library in the main Python distribution.

Grepping through some of the modules in the Python 3.5 standard library, alongside with the usual strings and numbers, one finds things like

UUIDs, uuid.py:

NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')

regular expressions, smtplib.py

OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I)

dictionaries, plistlib.py:

_BINARY_FORMAT = {1: 'B', 2: 'H', 4: 'L', 8: 'Q'}

frozensets, asyncore.py:

_DISCONNECTED = frozenset({ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED, EPIPE, ...

and a datetime.date in calendar.py

_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()

thus 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).

Mike - SMT

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 true constants, so we use the naming convention to help us remember not to change that value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!