簡體   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