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
	ConfigFile(lambda lvl, msg: print(msg), appname=__package__).load()

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

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.