Config and ConfigFile — confattr v0.4.0 documentation

# Config and ConfigFile

confattr (config attributes) is a python library to make applications configurable. This library defines the `Config` class to create attributes which can be changed in a config file. It uses the descriptor protocol to return it’s value when used as an instance attribute.

    from confattr import Config

    class Car:

    	speed_limit = Config('traffic-law.speed-limit', 50, unit='km/h')

    	def __init__(self) -> None:
    		self.speed = 0

    	def accelerate(self, value: int) -> None:
    		new_speed = self.speed + value
    		if new_speed > self.speed_limit:
    			raise ValueError('you are going too fast')

    		self.speed = new_speed

If you want to access the Config object itself you need to access it as a class attribute:

    	def print_config(self) -> None:
    		print('{key}: {val}'.format(key=type(self).speed_limit.key, val=self.speed_limit))

You load a config file with a `ConfigFile` object. In order to create an ConfigFile instance you need to provide a callback function which informs the user if the config file contains invalid lines. This callback function takes two arguments: (1) a `NotificationLevel` which says whether the notification is an error or an information and (2) the message to be presented to the user, either a `str` or a `BaseException`. When you load a config file with `ConfigFile.load()` all `Config` objects are updated automatically.

    if __name__ == '__main__':
    	from confattr import ConfigFile
    	config_file = ConfigFile(appname=__package__)
    	config_file.load()
    	config_file.set_ui_callback(lambda lvl, msg: print(msg))

    	c1 = Car()
    	print('speed_limit: %s' % c1.speed_limit)

Given the following config file (the location of the config file is determined by `ConfigFile.iter_config_paths()`):

    set traffic-law.speed-limit = 30

The script will give the following output:

    speed_limit: 30

Of course you don’t need to use classes. In that case you can access the value of a `Config` object via the `Config.value` attribute.