读取python dict或yaml,并将其称为Python参数和对象的python函数 [英] Read python dict or yaml and call as python function with arguments and objects

查看:170
本文介绍了读取python dict或yaml,并将其称为Python参数和对象的python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要阅读以下python dict或其等效的yaml并生成等效的python函数调用


To read the below python dict or its equivalent yaml and generate equivalent python function call

mydict = {'RouteAdd': {'route_config': {'RouteConfig': {'table_name': 'my table', 'app_id': 'my app', 'nexthops': [{'NexthopInfo': {'nexthop_index': 2, 'nexthop_address': {'GatewayAddress': {'ethernet_mac': 'my mac', 'nexthop_ip': 'my ip'}}, 'if_name': 'my interface'}}]}}}}

它的yaml(为了可读性):

Its yaml(for readability):

RouteAdd:
  route_config:
    RouteConfig:
      app_id: "my app"
      nexthops:
      - NexthopInfo:
          if_name: "my interface"
          nexthop_address:
            GatewayAddress:
              ethernet_mac: "my mac"
              nexthop_ip: "my ip"
          nexthop_index: 2
      table_name: "my table"

d喜欢阅读上述的yaml或python dict,并调用如下:

I would like to read the above kind of yaml or python dict and call as below:

RouteAdd(route_config=Routeconfig(app_id="my app",nexthops=[NexthopInfo(if_name="my interface",nexthop_address=GatewayAddress(ethernet_mac="my mac",nexthop_ip="my ip"),nexthop_index=2)],table_name="my table"))

基本上替代层次结构是一个对象。我粘贴的是一个小剪辑。寻找一个递归函数,通过读取yaml或python dict并将其转换为上述格式,以便我可以调用和执行该函数。任何帮助深表感谢。谢谢

Basically alternate hierarchy is an object. What I have pasted is a small clip. Looking for a recursive function that does this by reading either a yaml or python dict and convert it to above format so that I can call and execute the function. Any help is much appreciated. Thanks

推荐答案

尝试这样:

def call_dict(d):
    k, v = list(d.items())[0]  # ('RouteAdd', {route_config: ...})
    kwargs = {}
    for k2, v2 in v.items():
        if isinstance(v2, dict):
            kwargs[k2] = call_dict(v2)
        elif isinstance(v2, list):
            kwargs[k2] = [(call_dict(v3) if isinstance(v3, dict) else v3) for v3 in v2]
        else:
            kwargs[k2] = v2
    return globals()[k](**kwargs)

测试:

def test1(t_arg=None, t_arg2=None):
    return t_arg + sum(t_arg2)

def test2(t_arg=None):
    return t_arg


res = test1(t_arg=1, t_arg2=[test2(t_arg=2), test2(t_arg=3)])
print(res)  # 6


test_dict = {
    'test1': {
        't_arg': 1,
        't_arg2': [
            {'test2': {'t_arg': 2}},
            {'test2': {'t_arg': 3}},
        ]
    }
}

res = call_dict(test_dict)
print(res)  # 6

更新:

作为代码字符串:

def str_of_code(d):
    k, v = list(d.items())[0]
    kwargs = {}
    for k2, v2 in v.items():
        if isinstance(v2, dict):
            kwargs[k2] = str_of_code(v2)
        elif isinstance(v2, list):
            kwargs[k2] = '[{}]'.format(', '.join(
                (str_of_code(v3) if isinstance(v3, dict) else repr(v3)) for v3 in v2)
            )
        else:
            kwargs[k2] = repr(v2)
    return '{}({})'.format(k, ', '.join('{}={}'.format(*i) for i in kwargs.items()))


test_dict = {
    'test1': {
        't_arg': 1,
        't_arg2': [
            {'test2': {'t_arg': 2}},
            {'test2': {'t_arg': 3}},
        ]
    }
}

res = str_of_code(test_dict)
print(res)  # test1(t_arg=1, t_arg2=[test2(t_arg=2), test2(t_arg=3)])

这篇关于读取python dict或yaml,并将其称为Python参数和对象的python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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