I have a question similar to the question asked here: Importing a long list of constants to a Python file
Basically, I have a separate module which just contains a long list of constants, e.g.
constants.py
x = 1.2
y = 30.4
.
.
.
In another module, I would like import these constants and initialize them as instance attributes.
class.py
class something(object):
def __init__(self):
import constants
self.x = constants.x
self.y = constants.y
.
.
.
Is there an easier or more pythonic way to do this instead of retyping all of the variable names?
Python developers have developed a cool solution: it's called ConfigParser.
A practical example: config.ini
[constants]
key = value
x = 0
y = 1
class.py
from ConfigParser import SafeConfigParser
class MyClass(object):
def __init__(self, **kwargs):
self.config = SafeConfigParser(defaults=kwargs).read('config.ini')
def get_x(self):
return self.config.get('constants', 'x')
I hope this helps.
EDIT: If you need instance attributes, you can do:
class MyClass(object):
...
def __getattr__(self, key):
return self.config.get('constants', key)
EDIT2: need a Python file and a .ini file is not a solution?
from . import config
class Myclass(object):
def __getattr__(self, key):
return getattr(config, key)
You could do
for constant, value in constants.__dict__.values():
setattr(self, constant, value)
Why do you need them as instance attributes?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With