Set constant in Python

Asked

Viewed 11,601 times

12

How can I declare a constant in Python the same way I do in C with

#Define PI 3.1415

or in java

public final double PI = 3.1415
  • In case a tuple is created? pi = (3.141592)

  • This is the unique field for answers. If you have a question that was not answered, you can use the "Ask a question" button. In fact, the section you put does not define a tuple, because, in this case, parentheses will be used only for the management of operator precedence in the expression. To create a tuple you’d have to do pi = (3.141592,), comma, but that wouldn’t be semantic.

4 answers

16


In Python (in versions smaller than 3.8) this is not possible. Just create a variable and do not change its value.

PI = 3.1415

This second option would not have the same effect as a constant, since it is possible to rewrite a function in other parts of the code.

A workaround simple, if it really is much-needed have full assurance that this value will never be rewritten elsewhere in the code is to create a function that returns the desired value.

def const_pi():
    return 3.1415

  • 2

    Except if someone rewrites the function const_pi in another part of the haha code

  • @Andersoncarloswoss Truth. I think I was in the head that it was not possible to redefine functions.

  • LINQ, since it edited, would not be interesting to remove the suggestion to define a function since it does not guarantee that it is constant as it says in the reply?

12

There isn’t. Don’t forget that Python is a language of script, so it doesn’t need to supply all the mechanisms that other languages have.

The way is to:

alguma_coia = 10 #não mexa neste valor, ele deve ser constante 

10

As put in the other answers, Python, being a dynamic language, does not have the "constants" feature in a simple way: everything in Python is an object. When you define a literal number in Python code, actually, that number is a constant - the compiler that generates the bytecode puts its literal value in the . pyc -only that, by the nature of the language, any variable is only a name bound to an object -and at any time, you can simply link the name to another object.

In normal use, it is assumed that "Python is a language made to be used by adults who consent to what they are doing" - so a value declared in the body of a module, pointed out by a name with uppercase letters, is, by convention, treated as a constant, and the value of that variable should not be changed. Simple as that.

Understand if you have these two lines in your code, the value 3.141592 continues to exist in memory. Only the variable Pi will now reference a float object in another memory position:

Pi = 3.141592
Pi = Pi + 1

Now, Python allows almost limitless customization of the way data is accessed if they are attributes of a class (if they are variables of a module, the story is different, but hacks are possible).

Describing these mechanisms and suggesting various ways to create things similar to constants would be possible, but too advanced, and would be the size of a book chapter.

Instead, let’s stick to an example: the standard class "Enum" can be used to create classes with "constants" inside - which in addition to a value that cannot be changed directly, still has other properties like "readable name", among others:

import enum

class Numeros(enum.Enum):
    pi = 3.141592

print (Numeros.pi, Numeros.pi.value)

display:

(<Numeros.pi: 3.141592>, 3.141592)

And try to make:

Numeros.pi = 4

results in:

AttributeError: Cannot reassign members.

This Enum mechanism uses Python dynamism to do something that cannot be done in languages that have the "normal" constants you mention: at runtime it is possible to use the name of the constant. That is: in C it is impossible to print "PI" if you use a #define PI 3.141592 - once it defines it is a search and replace. Some libraries have support for using the C Enum in order to look at the name at runtime (I believe) - but in Python, just do:

print(Numeros.pi.name)

To see the printed "pi" text. And if you want to use the value numerically, you must use the attribute "value": print(Numeros.pi.value)

9

In version 3.8 of Python was added in the module typing the guy Final precisely to represent that a name may not be reallocated, but like all Python type annotation, this does not guarantee at runtime, only informs external type validation tools.

from typing import Final

PI: Final = 3.14159
PI = 4

print(PI)

When executing the above code you will have as output the value 4, as long as the name PI is a final value will not change the behavior at runtime. However, when executing the mypy in that same file you would get an error indicating that there is a reallocation at a final value.

(.env) ➜  mypy main.py 
main.py:4: error: Cannot assign to final name "PI"
Found 1 error in 1 file (checked 1 source file)

You can even use it in conjunction with another type to specify the actual type of the variable:

PI: Final[float] = 3.14

Browser other questions tagged

You are not signed in. Login or sign up in order to post.