如何避免在 python 3 中重新声明常量
How to avoid redeclaration of constants in python 3
我们有一个文件,其中有很多常量定义。当发生名称冲突时,python 会为其分配一个新值,而不会警告具有该名称的常量已经存在。这是错误的潜在来源。我们使用的静态代码分析器没有找到它(Sonarqube 和 pylint)。如何确保没有名称冲突?
PS:PyCharm加注"Redeclared defined above without usage",但我不使用PyCharm。
正如 Olvin Roght 所说,使用 typing.Final
from typing import Final
MAX_SIZE: Final = 9000
MAX_SIZE += 1 # Error reported by type checker
请注意,这将 return 类型检查器中的一个错误,但代码仍 运行 并且值仍会更改。
这需要Python 3.8+
或者你可以这样做:
from dataclasses import dataclass
@dataclass(frozen=True)
class Consts:
MAX_SIZE = 9000
myconsts = Consts()
myconsts.MAX_SIZE= 1 # generates an error
我们有一个文件,其中有很多常量定义。当发生名称冲突时,python 会为其分配一个新值,而不会警告具有该名称的常量已经存在。这是错误的潜在来源。我们使用的静态代码分析器没有找到它(Sonarqube 和 pylint)。如何确保没有名称冲突?
PS:PyCharm加注"Redeclared defined above without usage",但我不使用PyCharm。
正如 Olvin Roght 所说,使用 typing.Final
from typing import Final
MAX_SIZE: Final = 9000
MAX_SIZE += 1 # Error reported by type checker
请注意,这将 return 类型检查器中的一个错误,但代码仍 运行 并且值仍会更改。
这需要Python 3.8+
或者你可以这样做:
from dataclasses import dataclass
@dataclass(frozen=True)
class Consts:
MAX_SIZE = 9000
myconsts = Consts()
myconsts.MAX_SIZE= 1 # generates an error