How to evaluate simple math expressions in configuration files

I would like to use a configuration file with some simple math expressions like add or subtract.
For instance:

[section]
a = 10
b = 15
c = a-5
d = b+c

Is there a way to do this using the ConfigParser module? I found several examples of using strings as variables in configuration files, but if I use them, I get unrated strings (and I have to parse it in my Python code).

If this is not possible in ConfigParser, is there any module you recommend?

+3
source share
3 answers

Why use ConfigParser? Why not just

config.py:

a = 10
b = 15
c = a-5
d = b+c

script.py:

import config
print(config.c)
# 5
print(config.d)
# 20
+9
source

, , , Python. ( exec) . , , , , ( " .whateverrc.py..." ).

+2

- :

example.conf:

[section]
a = 10
b = 15
c = %(a)s+%(b)s
d = %(b)s+%(c)s

script :

import ConfigParser

config = ConfigParser.SafeConfigParser()
config.readfp(open('example.conf'))

print config.get('section', 'a')
# '10'
print config.get('section', 'b')
# '15'
print config.get('section', 'c')
# '10+15'
print config.get('section', 'd')
# '15+10+15'

:

print eval(config.get('section', 'c'))
# 25
print eval(config.get('section', 'd'))
# 40

, , ConfigParser , , get() , :

def my_get(self, section, option, eval_func=None):

    value = self.get(section, option)
    return eval_func(value) if eval_func else value

setattr(ConfigParser.SafeConfigParser, 'my_get', my_get)


print config.my_get('section', 'c', eval)
# 25

# Method like getint() and getfloat() can just be writing like this:

print config.my_get('section', 'a', int)
# 10
+2

Source: https://habr.com/ru/post/1784725/


All Articles