+ 2

how to I create a constant variable in python?

Like a variable value is fixed we can't to change the value

4th Nov 2022, 8:19 AM
SHAHEEN AHMED V
SHAHEEN AHMED V - avatar
4 Respuestas
+ 6
You can encapsulate your constant values in a frozen dataclass. This is a new feature from Python 3.7 Data classes typically carry some fields, and usually don't have any methods (although you can still write them). If you annotate a class with the dataclass decorator, the __init__ method is automatically created for you from the variables which are declared inside the class (with or without default value). The frozen flag makes these fields impossible to change, hence the instance is immutable and protected, the variables inside act like constants. https://code.sololearn.com/cgHqDuSPfsAI/?ref=app
4th Nov 2022, 10:43 AM
Tibor Santa
Tibor Santa - avatar
+ 2
In python, you can't declare a variable constant directly. Btw you can declare a function without argument and return a constant value. So when you call the function it will return a constant value. It's actually not declaring a constant variable though. https://code.sololearn.com/cr0zb02vy3if/?ref=app Edit: Yeah like Maisu said you can redeclare the function to change the value. So it actually doesn't work as a constant variable if you change the function. You can also check this question: https://stackoverflow.com/questions/2682745/how-do-i-create-a-constant-in-python
4th Nov 2022, 9:10 AM
The future is now thanks to science
The future is now thanks to science - avatar
+ 2
The future is now thanks to science You coule still change it with for example: constant = lambda:7
6th Nov 2022, 12:17 AM
Maisu
Maisu - avatar
+ 1
You can create a module and write constant values there. Constant name should be in All Capital letter.
4th Nov 2022, 8:44 AM
A͢J
A͢J - avatar