【问题标题】:Define a function head inside a conf file在 conf 文件中定义函数头
【发布时间】:2016-06-02 00:47:02
【问题描述】:

我在 Python 中使用字典/get 构造作为 switch case。它看起来和这个类似:

def switch_function(pluginID, param):
switcher = {
    'someid': somefunction(param),
}
return switch_function.get(pluginID, None)

但是,我想通过另一个键值对来扩展字典,该键值对在 conf 文件中定义。我想要一个函数头作为一个值。函数头应该是那个函数的头,它应该在switch case中执行,用于特定的pluginid。配置文件将如下所示:

[aSection]
pluginid='anotherid'
functionHead: anotherfunction2

扩展字典应该很容易,但是否可以将函数头映射为 conf 文件中的值?

【问题讨论】:

    标签: python dictionary switch-statement python-config


    【解决方案1】:

    以下示例将为您提供exec 子句。你的dict 应该是这样的:

    switcher[config["aSection"]["anotherid"])] = func
    

    然后你需要定义 func 看起来像这样:

    #CONF
    #[aSection]
    #pluginid='anotherid'
    #functionHead: anotherfunction2
    
    #PYTHON
    #config is an instance of a config parser
    def func (param):
      exec ("%s(param)" % config["aSection"]["functionHead"])
    

    这将调用您之前定义的名为anotherfunction2 的函数。像这样调用函数:

    switcher[config["aSection"]["anotherid"])](param)
    

    希望这会有所帮助!

    【讨论】:

    • 老实说,我没有完全理解您的解决方案,但它给了我一个提示,我该如何解决我的问题。我没有像你那样使用 exec,而是使用了 eval。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多