Skip to main content

Config file sections as objects

Project description

Latest PyPI Version License Downloads

Fileconfig turns config file sections into instances of your class. Create a class referring to an INI file collecting the arguments for the different instances to be created. Calling the class with the section name as parameter will return the instance with the parameters specified in the given section.

Installation

$ pip install fileconfig

Usage

Create as subclass of fileconfig.Config and set its filename attribute to the path of your INI file.

If the filename is relative, it is resolved relative to the path of the module where your class is defined (i.e. not relative to the current working directory if its file not happens do be there).

>>> import fileconfig

>>> class Cfg(fileconfig.Config):
...     filename = 'examples/pet-shop.ini'
...     def __init__(self, key, **kwargs):
...         self.key = key
...         self.__dict__.update(kwargs)
...     def __str__(self):
...         items = ('  %r: %r' % (k, v) for k, v in sorted(self.__dict__.iteritems()))
...         return '{\n%s\n}' % ',\n'.join(items)

On instance creation, the __init__ method will be called with the section name (key) and the keyword parameterss from the given section of the specified file.

Suppose your INI file begins like this:

[parrot]
species = Norwegian blue
can_talk = yes
quantity = 0
characteristics = beatiful plumage, pining for the fjords

To retrieve this instance, call the class with its section name.

>>> c = Cfg('parrot')

>>> print c
{
  'can_talk': 'yes',
  'characteristics': 'beatiful plumage, pining for the fjords',
  'key': 'parrot',
  'quantity': '0',
  'species': 'Norwegian blue'
}

Singleton

Only one instance will be created, cached and returned for each config file section (a.k.a. the singleton pattern):

>>> Cfg('parrot') is c
True

The constructor is also idempotent:

>>> Cfg(c) is c
True

The default __repr__ of instances allows roundtrips:

>>> c
__main__.Cfg('parrot')

Aliasing

You can specify a space-delimited list of aliases for each section:

[slug]
aliases = snail special_offer
species = slug
can_talk = no
quantity = 1

For changig the delimiter, see below.

Aliases map to the same instance:

>>> s = Cfg('special_offer')

>>> s
__main__.Cfg('slug')

>>> s is Cfg('snail') is Cfg('slug')
True

Inspect instance names (key + aliases):

>>> s.key
'slug'

>>> s.aliases
['snail', 'special_offer']

>>> s.names
['slug', 'snail', 'special_offer']

Inheritance

Config file sections can inherit from another section:

[polly]
inherits = parrot
can_talk = no
characteristics = dead, totally stiff, ceased to exist

Specified keys override inherited ones:

>>> print Cfg('polly')
{
  'can_talk': 'no',
  'characteristics': 'dead, totally stiff, ceased to exist',
  'inherits': 'parrot',
  'key': 'polly',
  'quantity': '0',
  'species': 'Norwegian blue'
}

Sections can inherit from a single section. Multiple or transitive inheritance is not supported.

Introspection

Use the class to iterate over the instances from all section:

>>> list(Cfg)
[__main__.Cfg('parrot'), __main__.Cfg('slug'), __main__.Cfg('polly')]

Print the string representation of all instances:

>>> Cfg.pprint_all()  # doctest: +ELLIPSIS
{
  'can_talk': 'yes',
  'characteristics': 'beatiful plumage, pining for the fjords',
  'key': 'parrot',
...

Hints

Apart from the key, aliases, and inherits parameters, your __init__ method receives the unprocessed strings from the config file parser.

Use the __init__ method to process the other parameters to fit your needs.

>>> class Pet(Cfg):
...     def __init__(self, can_talk, quantity, characteristics=None, **kwargs):
...         self.can_talk = {'yes':True, 'no': False}[can_talk]
...         self.quantity = int(quantity)
...         if characteristics is not None and characteristics.split():
...             self.characteristics = [c.strip() for c in characteristics.split(',')]
...         super(Pet, self).__init__(**kwargs)

>>> print Pet('polly')
{
  'can_talk': False,
  'characteristics': ['dead', 'totally stiff', 'ceased to exist'],
  'inherits': 'parrot',
  'key': 'polly',
  'quantity': 0,
  'species': 'Norwegian blue'
}

This way, the __init__ method also defines parameters as required or optional, set their defaults, etc.

Customization

To use a different delimiter for aliases override the _split_aliases method on your class. Make it a staticmethod or classmethod that takes a string argument and returns the splitted list.

By default, fileconfig will use ConfigParser.SafeConfigParser from the standard library to parse the config file. To use a different parser, override the _parser attribute in your fileconfig.Config subclass.

Fileconfig raises an error, if the config file is not found. If you want this error to pass silently instead, set the _pass_notfound atribute on your subclass to True.

License

Fileconfig is distributed under the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fileconfig-0.2.zip (14.1 kB view details)

Uploaded Source

File details

Details for the file fileconfig-0.2.zip.

File metadata

  • Download URL: fileconfig-0.2.zip
  • Upload date:
  • Size: 14.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for fileconfig-0.2.zip
Algorithm Hash digest
SHA256 68b693e8f1c93f6d2bad2f570ad7f6b64022979d50177bf79c47b37026a05dec
MD5 e9c4fc99dd16896d8d03bbccd184c6b5
BLAKE2b-256 655722791001986cd2421ed1f45fd0719470a9851ac3c70b699c592474c12a67

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page