Search code examples
pythonconstantsredeclaration

How to avoid redeclaration of constants in python 3


We have a file, where we have constant definitions and there are a lot of them. When there is a name collision, python assigns a new value to it without warning that constant with such name already exists. This is a potential source of bugs. Static code analyzers we use did not find it (Sonarqube and pylint). How to make sure that there are no name collisions?

PS: PyCharm raises "Redeclared defined above without usage", but I don't use PyCharm.


Solution

  • As Olvin Roght said use typing.Final

    from typing import Final
    MAX_SIZE: Final = 9000
    MAX_SIZE += 1 # Error reported by type checker
    

    Note that this will return an error in your type checker but the code would still run and the value would still change.

    This requires Python 3.8+


    Alternatively you can do:

    from dataclasses import dataclass
    @dataclass(frozen=True)
    class Consts:
      MAX_SIZE = 9000
    myconsts = Consts()
    myconsts.MAX_SIZE= 1 # generates an error