[Python] How can I implement true constants in Python?

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

    I'm attempting to use real constants in Python—values which cannot be modified once defined.

    I realize Python has no native support for constants like certain other languages (e.g., final in Java or const in C++), but I want the most Pythonic or safest manner of achieving this behavior.


    class Constants:
    PI = 3.14159
    GRAVITY = 9.8

    Constants.PI = 3 # This still allows reassignment


    I want something that raises an error or prevents the value from being changed. I’ve also heard of using custom classes or metaclasses, but I’m not sure what the best practice is.

    What’s the best way to implement unchangeable constants in Python?

    Continue reading...

Compartilhe esta Página