python包以简化包的配置
pkgsettings的Python项目详细描述
目标
这个包的目标是提供一个简单、通用和可扩展的方法 配置一个包。
安装
$ pip install pkgsettings
用法
frompkgsettingsimportSettings# Create the settings object for your package to usesettings=Settings()# Now let's define the default settingssettings.configure(hello='World',debug=False)
通过调用configure,您实际上注入了一个layer设置。 当请求设置时,它将遍历所有层,直到找到 请求的密钥。
现在如果有人开始使用你的包,它可以很容易地修改 通过再次调用配置来设置包。
frommy_awesome_package.confimportsettings# Lets change the configuration heresettings.configure(debug=True)
现在,您可以在软件包中使用如下设置:
fromconfimportsettingsprint(settings.debug)# This will print: Trueprint(settings.hello)# This will print: World
也可以传递对象而不是Kwargs。 设置对象将调用getattr(ur_object, key) 下面是一个示例:
classMySettings(object):def__init__(self):self.debug=Truesettings=Settings()settings.configure(MySettings())print(settings.debug)# This will print: True
更高级的用法
settings对象也可以用作上下文管理器:
withsettings(debug=True):print(settings.debug)# This will print: Trueprint(settings.debug)# This will print: False
此外,您还可以将其用作装饰器:
@settings(debug=True)defgo()print(settings.debug)# This will print: Truego()print(settings.debug)# This will print: False
前缀设置
如果一组设置共享一个公共前缀,则可以 使用PrefixedSettings类并传递所需的 前缀作为参数,与主设置实例一起使用。 访问时,所有属性都将自动加上前缀。
frompkgsettingsimportPrefixedSettings,Settings# First create the settings object for your package to usesettings=Settings()# Suppose some of your settings are all prefixed with 'FOO'settings.configure(FOO_a='a',FOO_b='b',c='c',debug=False)# Create a PrefixedSettings instance with the desired prefixfoo_settings=PrefixedSettings(settings,'FOO_')foo_settings.a# This will print: afoo_settings.b# This will print: bfoo_settings.c# This will raise an AttributeError