+ 5
Can a Python programmer do anything to ensure that a variable's value can never be changed after its initial assignment?
10 Respuestas
+ 8
I don't think so. Even if you use an immutable data type or create your own class of constant objects, nothing stops you from just assigning an arbitrary value to the variable/constant in the next step.
+ 8
A tuple is immutable.
+ 5
ALi Missaoui
But what if i 'trick' it like this
def VAR_NAME(): return 20
print(10+VAR_NAME())
x = VAR_NAME() # ok
VAR_NAME() = 5 # error
+ 5
E_E Mopho That's a nice trick, but VAR_NAME is not a variable and I doubt that using a function call as a variable name is good practice 😁
+ 5
Preston Mull I'm assuming the use-cases here would be the same as use-cases for constants in other languages.
Perhaps he was just curious if it was supported in Python.
+ 5
Kishalaya Saha That is a creative approach indeed. It reminds me of a code snippet I put together about 10 days ago to demonstrate NamedTuples.
https://code.sololearn.com/cz9q6M621LSy/?ref=app
NOTE: An exception will be thrown if attempting to change any of the values after initialization.
Your version allows for adding a property once at any time, but subsequent assignments to the same property with throw an exception.
Either way, I agree, when in Rome, do as the Romans do... (a.k.a. Learn to enjoy drinking the Python Kool-aid.) 😉
+ 4
Another attempt, inspired be Anna's idea of constant class.
class Const():
def __setattr__(self, c, val):
if c in vars(self):
raise Exception(f"Can't reassign to the constant {c}.")
vars(self)[c] = val
CONST = Const()
CONST.X = 42
CONST.Y = "spam"
print(f"X = {CONST.X}, Y = {CONST.Y}")
CONST.X = 2 # Error
Here we'll have to think of our constants as "CONST.NAME" instead of just NAME.
I don't really play with classes, so this could very well be wrong.
Either way, this is quite meaningless. I prefer the "We're all consenting adults here" approach. 😜
+ 3
Can the variable be an immutable type?
+ 2
Well, it's a variable, so why would it be necessary or how would code functionality utilize it if it is immutable? Not saying it shouldn't or cannot work, if possible in Python. Are you able to present or demonstrate a use-case, or suggest one?
+ 2
David Carroll, kool! 😉
So if we know all the constants we're going to use apriori (as is often the case), we can just put them all in a namedtuple. Nice!