+ 2
Is there a workaround to create a Constant in Python?
It might be sth. like myname = ("Frogged", ) print(*myname * 3) but it fails for numeric types https://code.sololearn.com/c1JlfSxtGEbp/?ref=app
6 Answers
+ 2
Here is a lot to read. But some ideas for workarounds.
https://stackoverflow.com/questions/2682745/how-do-i-create-a-constant-in-JUMP_LINK__&&__python__&&__JUMP_LINK/2682752
+ 2
Python doesn't have constants. There is only a convention to write them in upper case and not to change those.
Wrapping them in a tuple prevents changes as your code shows, but complicates usage a little
+ 2
Looking at how a constant works, i would say even this isnt a constant.
myname = ("Frogged",)
I believe a constant have something to do with a VARIABLE and their VALUES and not just VALUE as shown in your code.
Even though myname[0] looks like it's readonly, you can still change it's value using some random global.__dict__ method. You can also reassign the whole variable
myname = "%"
I doubt if there would be an actual solution to this cos i believe it has to do with how some variables are stored in memory. Python doesnt provide an api for that
+ 2
Lisa That was my idea too at first but it still can be modified.
Then I've read about defining a function on stackoverflow. Not very elegant, but it does the job i.e. workaround:
https://code.sololearn.com/cVZpz6PUv77p/?ref=app
+ 2
Just found this from Janusz Bujak 🇵🇱 🇺🇦
https://code.sololearn.com/clEi1D5gTrfA/?ref=app
+ 1
What about creating an extra file for the constants and then importing your "constants" from there?
# In an extra myconst.py
MYNAME = "Lisa"
# then in script:
from my constant import MYNAME
print(MYNAME)