在python类中使用configparser,好还是坏?

时间:2014-06-11 21:05:52

标签: python configparser

在类方法中使用ConfigParser是不好的做法吗?这样做意味着该类与配置绑定并且不易重复使用,但意味着方法中的输入参数较少,特别是如果参数必须向下传递多层,我会发现它很混乱。

有没有好的选择(除了将配置值作为方法参数传递)?或者人们发现的特定模式对此有用吗?

例如

# get shared config parser configured by main script
from utils.config_utils import config_parser

class FooClass(object):

    def foo_method(self):
        self._foo_bar_method()

    def _foo_bar_method(self):
        some_property = config_parser.get("root", "FooProperty")
        ....

1 个答案:

答案 0 :(得分:1)

如果你需要在一个类中有很多参数,这些参数可能是你试图对该类做太多的一个症状(参见SRP

如果确实需要一些配置选项太多而无法提供简单的类作为参数,我建议将配置抽象为一个单独的类并将其用作参数:

class Configuration(object):
    def __init__(self, config_parser):
        self.optionA = config_parser.get("root", "AProperty")
        self.optionB = config_parser.get("root", "BProperty")
        self.optionX = config_parser.get("root", "XProperty")

    @property
    def optionY(self):
        return self.optionX == 'something' and self.optionA > 10


class FooClass(object):
    def __init__(self, config):
        self._config = config

    def _foo_bar_method(self):
        some_property = self._config.optionY
        ....

config = Configuration(config_parser)
foo = FooClass(config)

通过这种方式,您可以重用配置抽象,甚至可以从同一个配置解析器为不同目的构建不同的配置抽象。

您甚至可以改进配置类,使其具有更具声明性的方式将配置属性映射到实例属性(但这是更高级的主题)。