python - 什么是 Python 中的常量?

标签 python python-3.x pep8

PEP 8 prescribes那个

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

我知道这只是一个命名约定,但我很想知道是否有官方或广泛接受的定义来说明常量与半私有(private)变量的实际构成。

这是否仅限于您所说的 mathematical constants ? (即float、int、complex)

或者它会包含诸如 datetime.date 对象或在模块级别定义的字符串之类的东西吗?具有混合类型的键/值的字典怎么样?如果答案是否定的,是否应该将这些类型的对象定义为带有 _leading_underscore 的(准)私有(private)变量?

最佳答案

嗯,PEP 8编码约定主要是Python 标准库编写的:

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

通过搜索 Python 3.5 标准库中的一些模块,以及常见的字符串和数字,可以找到像

UUIDs, uuid.py:

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

正则表达式,smtplib.py

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

字典,pliSTLib.py:

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

frozensets, asyncore.py:

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

calendar.py 中的datetime.date

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

因此基本上任何应该在整个执行期间保持不变的东西,即使它是可变类型(pliSTLib.py 中的字典)也是如此。

关于python - 什么是 Python 中的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46004474/

相关文章:

python - 如何将列表转换为字符串,然后在 python 中将其转换回?

python - 为什么交换奇数个变量列表时变量会消失?

python - 如何强制 iPython 使用旧版本的 Python?

python - pandas.DataFrame 上的成对行操作矩阵

python - 在python中使用字典用id替换字符串

Python:使用 4 个空格进行缩进。为什么?

python - PyCharm PEP8 类型参数违规

将数据导入数据库时​​出现 django-import-export 错误

python-3.x - 如何从 xid 获取 Gdk 窗口?

python - 三双引号 vs.双引号