繁体   English   中英

是否可以实例化一个知道其类型(元组/列表)的结构(元组/列表)?

[英]Is it possible to instantiate a structure (tuple/list) knowing its type (Tuple/List)?

我目前正在开发 python 代码来模拟某个 C 库。 感谢 pybind,我可以访问库函数和文档字符串。 任务是模拟这些函数的返回。

情况

到目前为止,我可以使用正则表达式成功读取任何 function output 。 现在,我需要评估此 output 的类型,获取此类型的内部内容并将其实例化为已知值或用 object 填充它。 这是我试图解释的一个例子:

docstring = parse(getattr(MyClass, the_method_I_want_to_mock).__doc__)

# The regex will read from -> to the end of the output hinting
method_type_search = re.search(r"(?<=-> ).+(?=)", docstring.short_description)

# If the regex finds something, evaluate the output
evaluated_method = eval(method_type_search.group(0))

此时, evaluated_method值将评估为: typing.Tuple[int, int]

问题

这就是我想要做的事情:
  1. 提取返回的类型
  2. 提取里面的内容(例如,如果我正在处理一个元组/列表)
  3. 使用步骤 1) 和 2) 创建实例化结构。 例如: typing.Tuple[int, int]将产生(0, 0)并且typing.List[float, user_class]将产生[0.0, user_class()]
这是我到目前为止所做的:
# eval_method is in the form of `typing.Tuple[int, int]` like aforementioned
def test_evaluate_types(eval_method):
    #This is the dictionary I plan on using to turn a type (ex: int) into its value (ex: 0). 
    #If any output requires an instantiated object (ex: typing.Tuple[user_class, int],
    #I'll need to instantiate the user_class and turn the int into 0.
    evaluate_dict: dict = { 
        int: 0,
        List[int]: [0, 1, 2]
    }
    out = []
    # checks if there is a structure or if its only one type (tuple[int, int] vs int)
    try:
        eval_method_type = eval_method._name
    except AttributeError:
        # if it's a simple type, return its value
        return evaluate_dict[eval_method]

    # This fetches what's inside a structure (ex: [<class 'int'>, <class 'int'>])
    eval_method_output = eval_method.__args__
    # parsing what is inside the structure and instanciating it.
    for idx, output in enumerate(eval_method_output):
        out.append(evaluate_dict[output])

#This WOULD casts the list into whatever structure was found earlier.
#It doesn't work and I'm stuck here.
return eval(eval_method_type + f"({out})") 

我觉得我可能会使我的问题复杂化,但似乎无法找到一种功能/方法来轻松地将任何类型(甚至用户类型)转换为如上所述的所选 output。

似乎可以使用__origin__ dunder 来获取必要的tuple 那么,当我有字符串Tuple[int, int]时,我会在它上面调用一个eval() ,这给了我typing.Tuple[int, int] 在 eval 的结果中使用 dunder __origin__ ,然后我得到我正在寻找的tuple并直接实例化它。

string_to_eval: str = "Tuple[int, int]"
string_eval = eval(string_to_eval)  # Yields the aforementionned typing.Tuple[int, int]
tuple_result = string_eval.__origin__()  # Yields 'tuple'

暂无
暂无

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

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