简体   繁体   English

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

[英]using configparser in python class, good or bad?

Is it bad practice to use a ConfigParser within class methods? 在类方法中使用ConfigParser是不好的做法吗? Doing this would mean the class is then tied to the config and not as easily re-usable, but means less input arguments in methods, which I would find messy especially if arguments had to be passed down multiple layers. 这样做将意味着该类随后被绑定到配置上,而不是那么容易重用,但是意味着方法中的输入参数更少,尤其是在参数必须向下传递多层的情况下,我会感到混乱。

Are there good alternatives (apart from just passing config values as method arguments)? 是否有很好的选择(除了仅将配置值作为方法参数传递外)? Or a particular pattern people find works well for this? 还是人们发现的特定模式对此很有效?

For example 例如

# 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")
        ....

If you need a lot of arguments in a single class that might be a symptom that you are trying to do too much with that class (see SRP ) 如果您在单个类中需要大量参数,这可能是您试图对该类进行过多处理的症状(请参见SRP

If there is indeed a real need for some configuration options that are too many to provide for a simple class as arguments I would advice to abstract the configuration as a separate class and use that as an argument: 如果确实确实需要一些配置选项,而这些配置选项太多了,无法提供一个简单的类作为参数,我建议将配置抽象为一个单独的类,并将其用作参数:

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)

In this way you can reuse your configuration abstraction or even build different configuration abstraction for different purposes from the same config parser. 通过这种方式,您可以重用您的配置抽象,甚至可以从同一配置解析器出于不同目的构建不同的配置抽象。

You can even improve the configuration class to have a more declarative way to map configuration properties to instance attributes (but that's more advanced topic). 您甚至可以改进配置类,使其具有更具声明性的方式来将配置属性映射到实例属性(但这是更高级的主题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM