+ 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

21st Apr 2021, 6:50 PM
Oma Falk
Oma Falk - avatar
6 Answers
21st Apr 2021, 7:16 PM
Coding Cat
Coding Cat - avatar
+ 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
21st Apr 2021, 7:30 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 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
21st Apr 2021, 10:54 PM
Mirielle - avatar
+ 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
22nd Apr 2021, 6:04 PM
Mihai Apostol
Mihai Apostol - avatar
12th Aug 2022, 10:08 AM
Mihai Apostol
Mihai Apostol - avatar
+ 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)
22nd Apr 2021, 5:50 PM
Lisa - avatar