python的层次化配置格式和上下文对象
python-wax的Python项目详细描述
python wax-python的分层配置格式和上下文对象
快速示例
>>> from wax import Wax, parse_wax >>> w = Wax(server=Wax(host='localhost')) >>> w.server.port = 1234 >>> print 'hostname is %(server.host)s using port %(server.port)s' % w hostname is localhost using port 1234 >>> s = str(w) >>> print s [server] host = "localhost" port = 1234 >>> w = parse_wax(s) print w [server] host = "localhost" port = 1234
功能
- 上下文对象可以序列化到/从字符串
- 简单的分层密钥结构
- 保持键顺序
- 值可以是任何json类型
- 支持注释和批注
概述
易于在代码中构造:
>>> w = Wax(message='hello world', num=17)
使用索引访问值:
>>> w['num'] = 18
>>> w.message = 'hello again'
>>> w.get('missing.key', 'no problem') 'no problem'
此对象直接转换为文件格式。正在读取格式 将完全重建上下文对象。这就允许 “往返”配置,可序列化为UTF-8、编辑和 读回:
>>> w = Wax(state='New York', zip=10003) >>> s = str(w) >>> print s state = "New York" zip = 10003 >>> q = parse_wax(s) >>> print q state = "New York" zip = 10003
单独添加密钥时,将保留密钥顺序。如果你加上它们 在构造函数中,初始顺序由kwargs(dict)散列控制 顺序:
>>> w = Wax(a=1, b=2, c=3) >>> print w a = 1 c = 3 b = 2 >>> w = Wax() >>> w.a = 1 >>> w.b = 2 >>> w.c = 3 >>> print w a = 1 b = 2 c = 3
通过将wax实例附加到密钥来创建子级:
>>> w = Wax(level1=Wax(level2=Wax(property='value')))
>>> w = Wax() >>> w.level1 = Wax() >>> w.level1.level2 = Wax() >>> w.level1.level2.property = 'value'
将此序列化:
>>> print w [level1.level2] property = "value"
或者可以设置点键来创建嵌套值:
>>> w = Wax() >>> w['foo.bar'] = 123 >>> print w.foo.bar 123
点式访问可用于格式化字符串:
>>> w = Wax(server=Wax(host='localhost', port=1234)) >>> print 'hostname is %(server.host)s using port %(server.port)s' % w hostname is localhost using port 1234