[英]How to poplulate a tuple list, preserving its structure in Python using for loop?
[英]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]
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.