Python:使用“点表示法"访问 YAML 值 [英] Python: Accessing YAML values using "dot notation"

查看:74
本文介绍了Python:使用“点表示法"访问 YAML 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 YAML 配置文件.所以这是在 Python 中加载我的配置的代码:

I'm using a YAML configuration file. So this is the code to load my config in Python:

import os
import yaml
with open('./config.yml') as file:
    config = yaml.safe_load(file)

这段代码实际上创建了一个字典.现在的问题是,为了访问这些值,我需要使用大量括号.

This code actually creates a dictionary. Now the problem is that in order to access the values I need to use tons of brackets.

YAML:

mysql:
    user:
        pass: secret

蟒蛇:

import os
import yaml
with open('./config.yml') as file:
    config = yaml.safe_load(file)
print(config['mysql']['user']['pass']) # <--

我更喜欢这样的东西(点符号):

I'd prefer something like that (dot notation):

config('mysql.user.pass')

所以,我的想法是利用 PyStache render() 接口.

So, my idea is to utilize the PyStache render() interface.

import os
import yaml
with open('./config.yml') as file:
    config = yaml.safe_load(file)

import pystache
def get_config_value( yml_path, config ):
    return pystache.render('{{' + yml_path + '}}', config)

get_config_value('mysql.user.pass', config)

这会是一个好的"解决方案吗?如果没有,有什么更好的选择?

Would that be a "good" solution? If not, what would be a better alternative?

其他问题[已解决]

我决定使用 Ilja Everilä 的解决方案.但现在我有一个额外的问题:您将如何围绕 DotConf 创建一个包装器 Config 类?

I've decided to use Ilja Everilä's solution. But now I've got an additional question: How would you create a wrapper Config class around DotConf?

以下代码不起作用,但我希望您明白我要做什么:

The following code doesn't work but I hope you get the idea what I'm trying to do:

class Config( DotDict ):
    def __init__( self ):
        with open('./config.yml') as file:
            DotDict.__init__(yaml.safe_load(file))

config = Config()
print(config.django.admin.user)

错误:

AttributeError: 'super' object has no attribute '__getattr__'

解决方案

你只需要将 self 传递给超类的构造函数即可.

You just need to pass self to the constructor of the super class.

DotDict.__init__(self, yaml.safe_load(file))

更好的解决方案 (Ilja Everilä)

super().__init__(yaml.safe_load(file))

推荐答案

The Simple

您可以使用 reduce 从配置中提取值:

The Simple

You could use reduce to extract the value from the config:

In [41]: config = {'asdf': {'asdf': {'qwer': 1}}}

In [42]: from functools import reduce
    ...: 
    ...: def get_config_value(key, cfg):
    ...:     return reduce(lambda c, k: c[k], key.split('.'), cfg)
    ...: 

In [43]: get_config_value('asdf.asdf.qwer', config)
Out[43]: 1

如果您的 YAML 使用非常有限的语言子集,则此解决方案易于维护并且几乎没有新的边缘情况.

This solution is easy to maintain and has very few new edge cases, if your YAML uses a very limited subset of the language.

使用适当的 YAML 解析器和工具,例如在这个答案中.

Use a proper YAML parser and tools, such as in this answer.

简单地说(不要太认真),您可以创建一个允许使用属性访问的包装器:

On a lighter note (not to be taken too seriously), you could create a wrapper that allows using attribute access:

In [47]: class DotConfig:
    ...:     
    ...:     def __init__(self, cfg):
    ...:         self._cfg = cfg
    ...:     def __getattr__(self, k):
    ...:         v = self._cfg[k]
    ...:         if isinstance(v, dict):
    ...:             return DotConfig(v)
    ...:         return v
    ...:     

In [48]: DotConfig(config).asdf.asdf.qwer
Out[48]: 1

请注意,这对于关键字失败,例如as"、pass"、if"等.

Do note that this fails for keywords, such as "as", "pass", "if" and the like.

最后,您可能会变得非常疯狂(阅读:可能不是一个好主意)并自定义 dict 以将带点的字符串和元组键作为特殊情况处理,对混合中的项目进行属性访问(有其局限性):

Finally, you could get really crazy (read: probably not a good idea) and customize dict to handle dotted string and tuple keys as a special case, with attribute access to items thrown in the mix (with its limitations):

In [58]: class DotDict(dict):
    ...:     
    ...:     # update, __setitem__ etc. omitted, but required if
    ...:     # one tries to set items using dot notation. Essentially
    ...:     # this is a read-only view.
    ...:
    ...:     def __getattr__(self, k):
    ...:         try:
    ...:             v = self[k]
    ...:         except KeyError:
    ...:             return super().__getattr__(k)
    ...:         if isinstance(v, dict):
    ...:             return DotDict(v)
    ...:         return v
    ...:
    ...:     def __getitem__(self, k):
    ...:         if isinstance(k, str) and '.' in k:
    ...:             k = k.split('.')
    ...:         if isinstance(k, (list, tuple)):
    ...:             return reduce(lambda d, kk: d[kk], k, self)
    ...:         return super().__getitem__(k)
    ...:
    ...:     def get(self, k, default=None):
    ...:         if isinstance(k, str) and '.' in k:
    ...:             try:
    ...:                 return self[k]
    ...:             except KeyError:
    ...:                 return default
    ...:         return super().get(k, default=default)
    ...:     

In [59]: dotconf = DotDict(config)

In [60]: dotconf['asdf.asdf.qwer']
Out[60]: 1

In [61]: dotconf['asdf', 'asdf', 'qwer']
Out[61]: 1

In [62]: dotconf.asdf.asdf.qwer
Out[62]: 1

In [63]: dotconf.get('asdf.asdf.qwer')
Out[63]: 1

In [64]: dotconf.get('asdf.asdf.asdf')

In [65]: dotconf.get('asdf.asdf.asdf', 'Nope')
Out[65]: 'Nope'

这篇关于Python:使用“点表示法"访问 YAML 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆