Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python initialization of constants in separate file

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?

like image 561
Manila Thrilla Avatar asked Oct 17 '25 07:10

Manila Thrilla


2 Answers

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)
like image 73
gioi Avatar answered Oct 20 '25 15:10

gioi


You could do

for constant, value in constants.__dict__.values():
  setattr(self, constant, value)

Why do you need them as instance attributes?

like image 43
Pavel Anossov Avatar answered Oct 20 '25 14:10

Pavel Anossov