0

Is it bad practice to use a ConfigParser within class methods? 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")
        ....
Michael S
  • 85
  • 6

1 Answers1

1

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)

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

Ion Scerbatiuc
  • 1,151
  • 6
  • 10
  • In the end I went with using class-wide attributes that I set during script initialisation from a config parser, for constant things like application paths, and generally method args for the rest. I think I might use your configuration class pattern later though as it seems quite nice and tidy. Thanks! – Michael S Jun 16 '14 at 19:30