+ 5

Can a Python programmer do anything to ensure that a variable's value can never be changed after its initial assignment?

17th Dec 2018, 5:27 PM
Pradeep Kumar
Pradeep Kumar - avatar
10 Antworten
+ 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.
17th Dec 2018, 6:01 PM
Anna
Anna - avatar
+ 8
A tuple is immutable.
27th Dec 2018, 8:58 PM
David Carroll
David Carroll - avatar
+ 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
28th Dec 2018, 6:29 AM
E_E Mopho
E_E Mopho - avatar
+ 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 😁
28th Dec 2018, 6:56 AM
Anna
Anna - avatar
+ 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.
28th Dec 2018, 10:11 PM
David Carroll
David Carroll - avatar
+ 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.) 😉
29th Dec 2018, 5:54 AM
David Carroll
David Carroll - avatar
+ 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. 😜
29th Dec 2018, 5:11 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
Can the variable be an immutable type?
17th Dec 2018, 5:48 PM
Kirk Schafer
Kirk Schafer - avatar
+ 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?
28th Dec 2018, 6:09 PM
Preston
Preston - avatar
+ 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!
29th Dec 2018, 6:03 AM
Kishalaya Saha
Kishalaya Saha - avatar