I want to control global variables (or globally scoped variables) in a way that they are set only once in program initialization code, and lock them after that.
I use UPPER_CASE_VARIABLES for global variables, but I want to have a sure way not to change the variable anyway.
- Does python provide that (or similar) feature?
- How do you control the globally scoped variables?
ActiveState has a recipe titled Cᴏɴsᴛᴀɴᴛs ɪɴ Pʏᴛʜᴏɴ by the venerable Alex Martelli for creating a
constmodule with attributes which cannot be rebound after creation. That sounds like what you’re looking for except for the upcasing — but that could be added by making it check to see whether the attribute name was all uppercase or not.Of course, this can be circumvented by the determined, but that’s the way Python is — and is considered to be a "good thing" by most folks. However, to make it a little more difficult, I suggest you don’t bother adding the supposedly obvious
__delattr__method since people could then just delete names and then add them back rebound to different values.This is what I’m taking about:
Put in
const.py:Output: