what is the best way to define constant variables python 3 what is the best way to define constant variables python 3 python python

what is the best way to define constant variables python 3


Python does not allow constant declarations like C or C++.

Normally in Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant.

Ex. MY_CONSTANT = "Whatever"

Another valid way of doing it which I don't use but heard of, is using a method:

def MY_CONSTANT():    return "Whatever"

Now in theory, calling MY_CONSTANT() acts just like a constant.

EDIT

Like the comments says, someone can go and change the value by calling

MY_CONSTANT = lambda: 'Something else'

but don't forget the same person can call MY_CONSTANT = "Something else" in the first example and change the initial value. In both cases it is unlikely but possible.


There are no constants in Python, the way they exist in C or Java. You can imitate them by functions:

def FOO():  return "foo"

You can wrap the function call in a property, and thus make it look like a variable:

class Const:  @property  def FOO(self):    return "foo"CONST = Const()  # You need an instanceif something == CONST.FOO:  ...

With a bit of meta stuff, one can get unsettable attributes with a terse syntax:

def const(cls):    # Replace a class's attributes with properties,    # and itself with an instance of its doppelganger.    is_special = lambda name: (name.startswith("__") and name.endswith("__"))    class_contents = {n: getattr(cls, n) for n in vars(cls) if not is_special(n)}    def unbind(value):  # Get the value out of the lexical closure.        return lambda self: value    propertified_contents = {name: property(unbind(value))                             for (name, value) in class_contents.items()}    receptor = type(cls.__name__, (object,), propertified_contents)    return receptor()  # Replace with an instance, so properties work.@constclass Paths(object):    home = "/home"    null = "/dev/null"

Now you can access Paths.home as a normal value, but can't assign to it. You can define several classes decorated with @const, as you might use several .h files.


Constants (in a sense) in Python 3.8+

Python 3.8 introduces the typing.Final type qualifier, which is used to indicate that a variable or attribute should not be reassigned, redefined, or overridden.

PEP 591 -- Adding a final qualifier to typing

from typing import Final# Annotate module variables# (with or without an explicit type, using the syntax Final[<type>])# (type is auto-determined in absence of an explicit type)PI: Final[float] = 3.141592654ANSWER_TO_EVERYTHING: Final = 42# Annotate instance variables in class bodies# (explicit type is needed if no value is assigned)class Point:    x: Final[int]    y: Final = 0    def __init__(self, x: int):        self.x = x# Annotate instance variables directly# (only allowed in __init__ methods)class Person:    def __init__(self, birth_year: int):        self.birth_year: Final = birth_year

Linters and type checkers will show you warnings if you reassign or redefine Final variables. Note that there is no runtime check, so you can still run the code below.

ANSWER_TO_EVERYTHING: Final = 42ANSWER_TO_EVERYTHING = 420  # shows warningprint(ANSWER_TO_EVERYTHING)  # prints 420

There is also the typing.final decorator, which is used to restrict inheriting classes and overriding methods.