what is the best way to define constant variables python 3
I am writing a program in python which contains many constant variables. I would like to create a file which will hold all these variables like .h file in C that contains many #define. I tried to use configparser however I didn't find it easy and fun to use.
Do you know a better way?
python python-3.x constants configuration-files
add a comment |
I am writing a program in python which contains many constant variables. I would like to create a file which will hold all these variables like .h file in C that contains many #define. I tried to use configparser however I didn't find it easy and fun to use.
Do you know a better way?
python python-3.x constants configuration-files
As far as configuration variables go, you can set environment variables and read them from within your code. You could also use JSON or YAML files.
– huck_cussler
May 25 at 17:17
related post: stackoverflow.com/questions/2682745/…
– Neil
Oct 18 at 10:02
add a comment |
I am writing a program in python which contains many constant variables. I would like to create a file which will hold all these variables like .h file in C that contains many #define. I tried to use configparser however I didn't find it easy and fun to use.
Do you know a better way?
python python-3.x constants configuration-files
I am writing a program in python which contains many constant variables. I would like to create a file which will hold all these variables like .h file in C that contains many #define. I tried to use configparser however I didn't find it easy and fun to use.
Do you know a better way?
python python-3.x constants configuration-files
python python-3.x constants configuration-files
edited May 25 at 17:34
9000
29.1k74582
29.1k74582
asked May 25 at 16:56
TomE8
7318
7318
As far as configuration variables go, you can set environment variables and read them from within your code. You could also use JSON or YAML files.
– huck_cussler
May 25 at 17:17
related post: stackoverflow.com/questions/2682745/…
– Neil
Oct 18 at 10:02
add a comment |
As far as configuration variables go, you can set environment variables and read them from within your code. You could also use JSON or YAML files.
– huck_cussler
May 25 at 17:17
related post: stackoverflow.com/questions/2682745/…
– Neil
Oct 18 at 10:02
As far as configuration variables go, you can set environment variables and read them from within your code. You could also use JSON or YAML files.
– huck_cussler
May 25 at 17:17
As far as configuration variables go, you can set environment variables and read them from within your code. You could also use JSON or YAML files.
– huck_cussler
May 25 at 17:17
related post: stackoverflow.com/questions/2682745/…
– Neil
Oct 18 at 10:02
related post: stackoverflow.com/questions/2682745/…
– Neil
Oct 18 at 10:02
add a comment |
3 Answers
3
active
oldest
votes
Python is not allowing constants declaration like in C or C++.
Normally in Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant.
Ex. MY_CONSTANT = "Whatever"
Another valid way of doing it which I don't use but heard of, is using a method:
def MY_CONSTANT():
return "Whatever"
Now in theory, calling MY_CONSTANT() acts just like a constant.
EDIT
Like the comments says, someone can go and change the value by calling
MY_CONSTANT = lambda: 'Something else'
but don't forget the same person can call MY_CONSTANT = "Something else" in the first example and change the initial value. In both cases it is unlikely but possible.
1
MY_CONSTANT = lambda: 'Something else'– Not sure why you'd bother with a "constant function", it's not any more constant.
– deceze♦
May 25 at 17:17
@scharette The point is that whether you usedeforlambda, you can still easily change the value ofMY_CONSTANT; it's just a name that refers to some object, whether that object be anintor afunction. Plus, the overhead of calling a function (both the lexical overhead of having to add()and the run-time overhead of setting up the stack frame) outweigh any perceived benefit.
– chepner
May 25 at 17:31
MY_CONSTANT = lambda: "new value"!is just as easy to write asMY_CONSTANT = "new value!"; making it a function doesn't do anything useful.
– chepner
May 25 at 17:33
You're right, this is not how I understood what he meant. I'm not trying to say this is a real constant, he's asking for C like constants, which doesn't exist in built-in python. My point is if someone is callingMY_CONSTANT = lambda: 'Something else'he really wants to change the value.
– scharette
May 25 at 17:36
Samething goes for someone changing the constant itself in C. I mean a constant is a constant until the day someone goes around and change the inital value...
– scharette
May 25 at 17:37
add a comment |
There are no constants in Python, the way they exist in C or Java. You can imitate them by functions:
def FOO():
return "foo"
You can wrap the function call in a property, and thus make it look like a variable:
class Const:
@property
def FOO(self):
return "foo"
CONST = Const() # You need an instance
if something == CONST.FOO:
...
With a bit of meta stuff, one can get unsettable attributes with a terse syntax:
def const(cls):
# Replace a class's attributes with properties,
# and itself with an instance of its doppelganger.
is_special = lambda name: (name.startswith("__") and name.endswith("__"))
class_contents = {n: getattr(cls, n) for n in vars(cls) if not is_special(n)}
def unbind(value): # Get the value out of the lexical closure.
return lambda self: value
propertified_contents = {name: property(unbind(value))
for (name, value) in class_contents.items()}
receptor = type(cls.__name__, (object,), propertified_contents)
return receptor() # Replace with an instance, so properties work.
@const
class Paths(object):
home = "/home"
null = "/dev/null"
Now you can access Paths.home as a normal value, but can't assign to it. You can define several classes decorated with @const, as you might use several .h files.
add a comment |
You can use something like this:
Files structure:
myapp/
__init__.py
settings.py
main.py
settings.py
CONST_A = 'A'
CONST_B = 'B'
__init__.py
from . import settings as global_settings
class Settings:
def __init__(self):
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))
def __setattr__(self, attr, value):
if not getattr(self, attr, None):
super().__setattr__(attr, value)
else:
raise TypeError("'constant' does not support item assignment")
settings = Settings()
main.py
import settings
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # raises TypeError error
print(settings.CONST_A) # prints A
settings.CONST_C = 'C' # also able to add new constants
print(settings.CONST_C) # prints C
Overwritten __setattr__ in Settings class makes all the attributes read-only.
The only requirement is to have all the constants in your settings.py written in capital letters.
But be aware, that it's not gonna work if you import variables directly:
from settings import CONST_A
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # sets C
print(settings.CONST_A) # prints C
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50533812%2fwhat-is-the-best-way-to-define-constant-variables-python-3%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Python is not allowing constants declaration like in C or C++.
Normally in Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant.
Ex. MY_CONSTANT = "Whatever"
Another valid way of doing it which I don't use but heard of, is using a method:
def MY_CONSTANT():
return "Whatever"
Now in theory, calling MY_CONSTANT() acts just like a constant.
EDIT
Like the comments says, someone can go and change the value by calling
MY_CONSTANT = lambda: 'Something else'
but don't forget the same person can call MY_CONSTANT = "Something else" in the first example and change the initial value. In both cases it is unlikely but possible.
1
MY_CONSTANT = lambda: 'Something else'– Not sure why you'd bother with a "constant function", it's not any more constant.
– deceze♦
May 25 at 17:17
@scharette The point is that whether you usedeforlambda, you can still easily change the value ofMY_CONSTANT; it's just a name that refers to some object, whether that object be anintor afunction. Plus, the overhead of calling a function (both the lexical overhead of having to add()and the run-time overhead of setting up the stack frame) outweigh any perceived benefit.
– chepner
May 25 at 17:31
MY_CONSTANT = lambda: "new value"!is just as easy to write asMY_CONSTANT = "new value!"; making it a function doesn't do anything useful.
– chepner
May 25 at 17:33
You're right, this is not how I understood what he meant. I'm not trying to say this is a real constant, he's asking for C like constants, which doesn't exist in built-in python. My point is if someone is callingMY_CONSTANT = lambda: 'Something else'he really wants to change the value.
– scharette
May 25 at 17:36
Samething goes for someone changing the constant itself in C. I mean a constant is a constant until the day someone goes around and change the inital value...
– scharette
May 25 at 17:37
add a comment |
Python is not allowing constants declaration like in C or C++.
Normally in Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant.
Ex. MY_CONSTANT = "Whatever"
Another valid way of doing it which I don't use but heard of, is using a method:
def MY_CONSTANT():
return "Whatever"
Now in theory, calling MY_CONSTANT() acts just like a constant.
EDIT
Like the comments says, someone can go and change the value by calling
MY_CONSTANT = lambda: 'Something else'
but don't forget the same person can call MY_CONSTANT = "Something else" in the first example and change the initial value. In both cases it is unlikely but possible.
1
MY_CONSTANT = lambda: 'Something else'– Not sure why you'd bother with a "constant function", it's not any more constant.
– deceze♦
May 25 at 17:17
@scharette The point is that whether you usedeforlambda, you can still easily change the value ofMY_CONSTANT; it's just a name that refers to some object, whether that object be anintor afunction. Plus, the overhead of calling a function (both the lexical overhead of having to add()and the run-time overhead of setting up the stack frame) outweigh any perceived benefit.
– chepner
May 25 at 17:31
MY_CONSTANT = lambda: "new value"!is just as easy to write asMY_CONSTANT = "new value!"; making it a function doesn't do anything useful.
– chepner
May 25 at 17:33
You're right, this is not how I understood what he meant. I'm not trying to say this is a real constant, he's asking for C like constants, which doesn't exist in built-in python. My point is if someone is callingMY_CONSTANT = lambda: 'Something else'he really wants to change the value.
– scharette
May 25 at 17:36
Samething goes for someone changing the constant itself in C. I mean a constant is a constant until the day someone goes around and change the inital value...
– scharette
May 25 at 17:37
add a comment |
Python is not allowing constants declaration like in C or C++.
Normally in Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant.
Ex. MY_CONSTANT = "Whatever"
Another valid way of doing it which I don't use but heard of, is using a method:
def MY_CONSTANT():
return "Whatever"
Now in theory, calling MY_CONSTANT() acts just like a constant.
EDIT
Like the comments says, someone can go and change the value by calling
MY_CONSTANT = lambda: 'Something else'
but don't forget the same person can call MY_CONSTANT = "Something else" in the first example and change the initial value. In both cases it is unlikely but possible.
Python is not allowing constants declaration like in C or C++.
Normally in Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant.
Ex. MY_CONSTANT = "Whatever"
Another valid way of doing it which I don't use but heard of, is using a method:
def MY_CONSTANT():
return "Whatever"
Now in theory, calling MY_CONSTANT() acts just like a constant.
EDIT
Like the comments says, someone can go and change the value by calling
MY_CONSTANT = lambda: 'Something else'
but don't forget the same person can call MY_CONSTANT = "Something else" in the first example and change the initial value. In both cases it is unlikely but possible.
edited Nov 12 at 14:57
answered May 25 at 17:11
scharette
4,91431339
4,91431339
1
MY_CONSTANT = lambda: 'Something else'– Not sure why you'd bother with a "constant function", it's not any more constant.
– deceze♦
May 25 at 17:17
@scharette The point is that whether you usedeforlambda, you can still easily change the value ofMY_CONSTANT; it's just a name that refers to some object, whether that object be anintor afunction. Plus, the overhead of calling a function (both the lexical overhead of having to add()and the run-time overhead of setting up the stack frame) outweigh any perceived benefit.
– chepner
May 25 at 17:31
MY_CONSTANT = lambda: "new value"!is just as easy to write asMY_CONSTANT = "new value!"; making it a function doesn't do anything useful.
– chepner
May 25 at 17:33
You're right, this is not how I understood what he meant. I'm not trying to say this is a real constant, he's asking for C like constants, which doesn't exist in built-in python. My point is if someone is callingMY_CONSTANT = lambda: 'Something else'he really wants to change the value.
– scharette
May 25 at 17:36
Samething goes for someone changing the constant itself in C. I mean a constant is a constant until the day someone goes around and change the inital value...
– scharette
May 25 at 17:37
add a comment |
1
MY_CONSTANT = lambda: 'Something else'– Not sure why you'd bother with a "constant function", it's not any more constant.
– deceze♦
May 25 at 17:17
@scharette The point is that whether you usedeforlambda, you can still easily change the value ofMY_CONSTANT; it's just a name that refers to some object, whether that object be anintor afunction. Plus, the overhead of calling a function (both the lexical overhead of having to add()and the run-time overhead of setting up the stack frame) outweigh any perceived benefit.
– chepner
May 25 at 17:31
MY_CONSTANT = lambda: "new value"!is just as easy to write asMY_CONSTANT = "new value!"; making it a function doesn't do anything useful.
– chepner
May 25 at 17:33
You're right, this is not how I understood what he meant. I'm not trying to say this is a real constant, he's asking for C like constants, which doesn't exist in built-in python. My point is if someone is callingMY_CONSTANT = lambda: 'Something else'he really wants to change the value.
– scharette
May 25 at 17:36
Samething goes for someone changing the constant itself in C. I mean a constant is a constant until the day someone goes around and change the inital value...
– scharette
May 25 at 17:37
1
1
MY_CONSTANT = lambda: 'Something else' – Not sure why you'd bother with a "constant function", it's not any more constant.– deceze♦
May 25 at 17:17
MY_CONSTANT = lambda: 'Something else' – Not sure why you'd bother with a "constant function", it's not any more constant.– deceze♦
May 25 at 17:17
@scharette The point is that whether you use
def or lambda, you can still easily change the value of MY_CONSTANT; it's just a name that refers to some object, whether that object be an int or a function. Plus, the overhead of calling a function (both the lexical overhead of having to add () and the run-time overhead of setting up the stack frame) outweigh any perceived benefit.– chepner
May 25 at 17:31
@scharette The point is that whether you use
def or lambda, you can still easily change the value of MY_CONSTANT; it's just a name that refers to some object, whether that object be an int or a function. Plus, the overhead of calling a function (both the lexical overhead of having to add () and the run-time overhead of setting up the stack frame) outweigh any perceived benefit.– chepner
May 25 at 17:31
MY_CONSTANT = lambda: "new value"! is just as easy to write as MY_CONSTANT = "new value!"; making it a function doesn't do anything useful.– chepner
May 25 at 17:33
MY_CONSTANT = lambda: "new value"! is just as easy to write as MY_CONSTANT = "new value!"; making it a function doesn't do anything useful.– chepner
May 25 at 17:33
You're right, this is not how I understood what he meant. I'm not trying to say this is a real constant, he's asking for C like constants, which doesn't exist in built-in python. My point is if someone is calling
MY_CONSTANT = lambda: 'Something else' he really wants to change the value.– scharette
May 25 at 17:36
You're right, this is not how I understood what he meant. I'm not trying to say this is a real constant, he's asking for C like constants, which doesn't exist in built-in python. My point is if someone is calling
MY_CONSTANT = lambda: 'Something else' he really wants to change the value.– scharette
May 25 at 17:36
Samething goes for someone changing the constant itself in C. I mean a constant is a constant until the day someone goes around and change the inital value...
– scharette
May 25 at 17:37
Samething goes for someone changing the constant itself in C. I mean a constant is a constant until the day someone goes around and change the inital value...
– scharette
May 25 at 17:37
add a comment |
There are no constants in Python, the way they exist in C or Java. You can imitate them by functions:
def FOO():
return "foo"
You can wrap the function call in a property, and thus make it look like a variable:
class Const:
@property
def FOO(self):
return "foo"
CONST = Const() # You need an instance
if something == CONST.FOO:
...
With a bit of meta stuff, one can get unsettable attributes with a terse syntax:
def const(cls):
# Replace a class's attributes with properties,
# and itself with an instance of its doppelganger.
is_special = lambda name: (name.startswith("__") and name.endswith("__"))
class_contents = {n: getattr(cls, n) for n in vars(cls) if not is_special(n)}
def unbind(value): # Get the value out of the lexical closure.
return lambda self: value
propertified_contents = {name: property(unbind(value))
for (name, value) in class_contents.items()}
receptor = type(cls.__name__, (object,), propertified_contents)
return receptor() # Replace with an instance, so properties work.
@const
class Paths(object):
home = "/home"
null = "/dev/null"
Now you can access Paths.home as a normal value, but can't assign to it. You can define several classes decorated with @const, as you might use several .h files.
add a comment |
There are no constants in Python, the way they exist in C or Java. You can imitate them by functions:
def FOO():
return "foo"
You can wrap the function call in a property, and thus make it look like a variable:
class Const:
@property
def FOO(self):
return "foo"
CONST = Const() # You need an instance
if something == CONST.FOO:
...
With a bit of meta stuff, one can get unsettable attributes with a terse syntax:
def const(cls):
# Replace a class's attributes with properties,
# and itself with an instance of its doppelganger.
is_special = lambda name: (name.startswith("__") and name.endswith("__"))
class_contents = {n: getattr(cls, n) for n in vars(cls) if not is_special(n)}
def unbind(value): # Get the value out of the lexical closure.
return lambda self: value
propertified_contents = {name: property(unbind(value))
for (name, value) in class_contents.items()}
receptor = type(cls.__name__, (object,), propertified_contents)
return receptor() # Replace with an instance, so properties work.
@const
class Paths(object):
home = "/home"
null = "/dev/null"
Now you can access Paths.home as a normal value, but can't assign to it. You can define several classes decorated with @const, as you might use several .h files.
add a comment |
There are no constants in Python, the way they exist in C or Java. You can imitate them by functions:
def FOO():
return "foo"
You can wrap the function call in a property, and thus make it look like a variable:
class Const:
@property
def FOO(self):
return "foo"
CONST = Const() # You need an instance
if something == CONST.FOO:
...
With a bit of meta stuff, one can get unsettable attributes with a terse syntax:
def const(cls):
# Replace a class's attributes with properties,
# and itself with an instance of its doppelganger.
is_special = lambda name: (name.startswith("__") and name.endswith("__"))
class_contents = {n: getattr(cls, n) for n in vars(cls) if not is_special(n)}
def unbind(value): # Get the value out of the lexical closure.
return lambda self: value
propertified_contents = {name: property(unbind(value))
for (name, value) in class_contents.items()}
receptor = type(cls.__name__, (object,), propertified_contents)
return receptor() # Replace with an instance, so properties work.
@const
class Paths(object):
home = "/home"
null = "/dev/null"
Now you can access Paths.home as a normal value, but can't assign to it. You can define several classes decorated with @const, as you might use several .h files.
There are no constants in Python, the way they exist in C or Java. You can imitate them by functions:
def FOO():
return "foo"
You can wrap the function call in a property, and thus make it look like a variable:
class Const:
@property
def FOO(self):
return "foo"
CONST = Const() # You need an instance
if something == CONST.FOO:
...
With a bit of meta stuff, one can get unsettable attributes with a terse syntax:
def const(cls):
# Replace a class's attributes with properties,
# and itself with an instance of its doppelganger.
is_special = lambda name: (name.startswith("__") and name.endswith("__"))
class_contents = {n: getattr(cls, n) for n in vars(cls) if not is_special(n)}
def unbind(value): # Get the value out of the lexical closure.
return lambda self: value
propertified_contents = {name: property(unbind(value))
for (name, value) in class_contents.items()}
receptor = type(cls.__name__, (object,), propertified_contents)
return receptor() # Replace with an instance, so properties work.
@const
class Paths(object):
home = "/home"
null = "/dev/null"
Now you can access Paths.home as a normal value, but can't assign to it. You can define several classes decorated with @const, as you might use several .h files.
edited May 25 at 18:13
answered May 25 at 17:51
9000
29.1k74582
29.1k74582
add a comment |
add a comment |
You can use something like this:
Files structure:
myapp/
__init__.py
settings.py
main.py
settings.py
CONST_A = 'A'
CONST_B = 'B'
__init__.py
from . import settings as global_settings
class Settings:
def __init__(self):
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))
def __setattr__(self, attr, value):
if not getattr(self, attr, None):
super().__setattr__(attr, value)
else:
raise TypeError("'constant' does not support item assignment")
settings = Settings()
main.py
import settings
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # raises TypeError error
print(settings.CONST_A) # prints A
settings.CONST_C = 'C' # also able to add new constants
print(settings.CONST_C) # prints C
Overwritten __setattr__ in Settings class makes all the attributes read-only.
The only requirement is to have all the constants in your settings.py written in capital letters.
But be aware, that it's not gonna work if you import variables directly:
from settings import CONST_A
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # sets C
print(settings.CONST_A) # prints C
add a comment |
You can use something like this:
Files structure:
myapp/
__init__.py
settings.py
main.py
settings.py
CONST_A = 'A'
CONST_B = 'B'
__init__.py
from . import settings as global_settings
class Settings:
def __init__(self):
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))
def __setattr__(self, attr, value):
if not getattr(self, attr, None):
super().__setattr__(attr, value)
else:
raise TypeError("'constant' does not support item assignment")
settings = Settings()
main.py
import settings
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # raises TypeError error
print(settings.CONST_A) # prints A
settings.CONST_C = 'C' # also able to add new constants
print(settings.CONST_C) # prints C
Overwritten __setattr__ in Settings class makes all the attributes read-only.
The only requirement is to have all the constants in your settings.py written in capital letters.
But be aware, that it's not gonna work if you import variables directly:
from settings import CONST_A
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # sets C
print(settings.CONST_A) # prints C
add a comment |
You can use something like this:
Files structure:
myapp/
__init__.py
settings.py
main.py
settings.py
CONST_A = 'A'
CONST_B = 'B'
__init__.py
from . import settings as global_settings
class Settings:
def __init__(self):
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))
def __setattr__(self, attr, value):
if not getattr(self, attr, None):
super().__setattr__(attr, value)
else:
raise TypeError("'constant' does not support item assignment")
settings = Settings()
main.py
import settings
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # raises TypeError error
print(settings.CONST_A) # prints A
settings.CONST_C = 'C' # also able to add new constants
print(settings.CONST_C) # prints C
Overwritten __setattr__ in Settings class makes all the attributes read-only.
The only requirement is to have all the constants in your settings.py written in capital letters.
But be aware, that it's not gonna work if you import variables directly:
from settings import CONST_A
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # sets C
print(settings.CONST_A) # prints C
You can use something like this:
Files structure:
myapp/
__init__.py
settings.py
main.py
settings.py
CONST_A = 'A'
CONST_B = 'B'
__init__.py
from . import settings as global_settings
class Settings:
def __init__(self):
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))
def __setattr__(self, attr, value):
if not getattr(self, attr, None):
super().__setattr__(attr, value)
else:
raise TypeError("'constant' does not support item assignment")
settings = Settings()
main.py
import settings
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # raises TypeError error
print(settings.CONST_A) # prints A
settings.CONST_C = 'C' # also able to add new constants
print(settings.CONST_C) # prints C
Overwritten __setattr__ in Settings class makes all the attributes read-only.
The only requirement is to have all the constants in your settings.py written in capital letters.
But be aware, that it's not gonna work if you import variables directly:
from settings import CONST_A
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # sets C
print(settings.CONST_A) # prints C
answered May 25 at 18:20
Artem Nepo
16318
16318
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50533812%2fwhat-is-the-best-way-to-define-constant-variables-python-3%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
As far as configuration variables go, you can set environment variables and read them from within your code. You could also use JSON or YAML files.
– huck_cussler
May 25 at 17:17
related post: stackoverflow.com/questions/2682745/…
– Neil
Oct 18 at 10:02