简体   繁体   English

将参数传递给变量引用的函数

[英]Passing arguments to a function referenced by a variable

The Issue 问题

I am writing a file parser for program input files that can be somewhat deconstructed to dictionaries: that is, in the input file, there are multi-level 'dicts' containing 'key-value pairs'. 我正在为程序输入文件编写一个文件解析器,该文件解析器可以稍微分解为字典:也就是说,在输入文件中,存在包含“键-值对”的多级“字典”。

I have a keywords dictionary which tells a read function which keys to read, and how to parse the key values. 我有一个关键字字典,它告诉read函数要读取哪些键以及如何解析键值。

For example, you can see in the code excerpt below that when datum is read, the value should be parsed with the function HelperFunctions.split_to_floats : 例如,您可以在下面的代码摘录中看到,当读取datum时,应使用HelperFunctions.split_to_floats函数解析该值:

'datum': HelperFunctions.split_to_floats

The Goal 目标

What I would like to do is be able to pass in arguments, such that I do not have to make function permutations for each possible type of ie value delimiter. 我想做的是能够传递参数,这样我就不必为每种可能的类型(即值定界符)进行函数排列。

For example, to restructure the keywords dictionary in something like: 例如,以如下方式重组keywords字典:

keywords = {
    '_root': str,
    'units': HelperFunctions._split(LINE,to=str,delim=','),
    'datum': HelperFunctions._split(LINE,to=float,delim=' ')
    }

Code Sample 代码样例

A full, workable demo of what I currently have is reproduced below: 以下是我目前所拥有的完整,可行的演示:

class HelperFunctions:

    def comma_split_to_strings(string:str) -> list:
        # Returns a list of strings
        return string.split(',')

    def split_to_floats(string:str) -> list:
        # Returns a 1D list of floats
        return list(map(float,string.split()))


keywords = {
    '_root': str,
    'units': HelperFunctions.comma_split_to_strings,
    'datum': HelperFunctions.split_to_floats
    }

card = {}
key = 'units'
value = 'Pa,kg,km'

if key in keywords:
    cast = keywords[key]

    card[key] = cast(value)

What you are looking for is partial in functools. 您所寻找的只是部分 functools。 It lets you create a function with some of parameters bound to values such that you can call the returned function later with the missing values. 它使您可以创建带有绑定到值的某些参数的函数,以便稍后可以使用缺少的值调用返回的函数。

from functools import partial

# Bind the parameters you want to "freeze"
keywords = {
    '_root': str,
    'units': partial(HelperFunctions._split, to=str, delim=','),
    'datum': partial(HelperFunctions._split, to=float, delim=' ')
    }

# The later you just need to provide LINE
keywords['units'](LINE)

Are you looking for functools.partial ? 您在寻找functools.partial吗?

from functools import partial

keywords = {
    '_root': str,
    'units': partial(HelperFunctions._split, to=str, delim=','),
    'datum': partial(HelperFunctions._split, to=float, delim=' ')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM