In [1]:
content = '''!Config
  title: config title
  description: this is an example config. configyml support tree structure.
  tree: !Config
    a: 
      - 1
      - !Config
        b: 2
        c: 3
    d: 4
'''
with open('config.yml', 'w') as f:
    f.write(content)

Basic Usage

In [2]:
from configyml import set_path
set_path('config.yml')
In [3]:
from configyml import arg
print(arg)
!Config
description: this is an example config. configyml support tree structure.
title: config title
tree: !Config
  a:
  - 1
  - !Config
    b: 2
    c: 3
  d: 4

In [4]:
print(arg.tree.a[1].b)
2

The Config Object

In [5]:
from configyml import Config

Create a Config Object

In [6]:
config = Config(
    title='title example', 
    description='this is an example config.',
    nest=Config(
        description='also support nested structure.'
    )
)
config
Out[6]:
!Config
description: this is an example config.
nest: !Config
  description: also support nested structure.
title: title example

Serialize

In [7]:
import yaml
s = yaml.dump(config)
In [8]:
from configyml import dump
s = yaml.dump(config)
In [9]:
dump == yaml.dump
Out[9]:
True

Some useful methods

In [10]:
print(len(config), '\n')
for key, val in config:
    print(key)
    print(val)
    print()
3 

description
this is an example config.

nest
!Config
description: also support nested structure.


title
title example

Usage with argparse

The Config Object inherit the argument structure Namespace of our beloved argparse module.
So, serialize your arguments with ease.

In [11]:
import argparse
argparse.Namespace = Config
In [12]:
# An example modified from https://docs.python.org/3/library/argparse.html

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args('1 2 3 4 5 --sum'.split())
print(args)

args.accumulate(args.integers)
!Config
accumulate: !!python/name:builtins.sum ''
integers: [1, 2, 3, 4, 5]

Out[12]:
15

Inherit Config and write your own class

In [13]:
from configyml import register
In [14]:
@register
class MyConfig(Config):
    def __getitem__(self, item):
        return self.__dict__[item]
In [15]:
content = '''!Config
  title: config title
  myconfig: !MyConfig
    a: 3
    b: 4
    c: 5
'''
myconfig = yaml.load(content).myconfig
myconfig
Out[15]:
!MyConfig
a: 3
b: 4
c: 5
In [16]:
myconfig['c']
Out[16]:
5