我有一個 python 程式(或函式),我想用不同的引數值呼叫它。
假設函式是:
myfunc(x = 0,y = 0,z =0, w=0, ...):
我使用這樣的命令列來設定引數:
run x=2#3#4--y=1#2--z=5
它顯示 x、y 和 z 的值(引數的數量不固定,許多可能有默認值,我想設定任意一組)。我想用所有組合呼叫該函式,例如x=2, y=1, z=5
. 對于此示例,有 6 種組合。
我嘗試用回圈撰寫它,但我認為它必須遞回撰寫,因為在回圈中我不知道何時為下一次運行設定和取消設定變數。
all_vars = var.split("--")
cont = True
while cont:
ii = 0
for _var in all_vars:
_var_name,_var_item_list = _var.split("=")
_var_item_list = _var_item_list.split("#")
cont = False
for var_item in _var_item_list:
if not _var_name in args or args[_var_name] != var_item
args[_var_name] = var_item
_output_name = "_" _var_name "_" str(var_item)
cont = True
ii = 1
break
else:
continue
if cont and ii == len(all_vars):
ctx.invoke(run, **args) # calling the function
uj5u.com熱心網友回復:
我通常在測驗場景中這樣做,但使用 pytest:
@pytest.mark.parametrize('bar', ['a', 'b', 'c'])
@pytest.mark.parametrize('_x', [1, 2, 3])
def test_foo(bar:str, _x: int):
print(bar, _x)
此代碼將使用所有引陣列合執行函式測驗:
============================= test session starts ==============================
collecting ... collected 9 items
test_static_models.py::test_foo[1-a]
test_static_models.py::test_foo[1-b]
test_static_models.py::test_foo[1-c]
test_static_models.py::test_foo[2-a]
test_static_models.py::test_foo[2-b]
test_static_models.py::test_foo[2-c]
test_static_models.py::test_foo[3-a]
test_static_models.py::test_foo[3-b]
test_static_models.py::test_foo[3-c]
uj5u.com熱心網友回復:
我認為您可以通過以下方式執行此操作
import itertools
import inspect
def fun(x,y,z, d=3):
print(x,y,z)
return x y z
params = inspect.signature(fun).parameters # paramters of your function
a = "x=2#3#4--y=1#2--z=5".split("--")
var_names = [x.split("=")[0] for x in a]
values = [map(int, x.split("=")[1].split("#")) for x in a]
tot_comb = [dict(zip(var_names, comb)) for comb in itertools.product(*values)]
for comb in tot_comb:
print(fun(**comb))
如果您想檢查您的函式是否可以使用給定的關鍵字引數呼叫,我已經為用例包含了檢查模塊
uj5u.com熱心網友回復:
你可以這樣做,沒有圖書館:
var = "x=2#3#4--y=1#2--z=5"
var = {var_bloc[:var_bloc.index("=")]: var_bloc[var_bloc.index("=") 1:].split("#") for var_bloc in var.split("--")}
#Here var will be {"x":['2', '3', '4'], "y": ['1', '2'], "z": ['5']}
def enumerate_possibility(params):
if len(params) == 1:
for k, possible_values in params.items():
for val in possible_values:
yield {k:val}
else:
key, possible_values = list(params.items())[0]
for val in possible_values:
for item in enumerate_possibility({k:v for k, v in params.items() if k != key}):
yield {key:val, **item}
for possible_param in enumerate_possibility(var):
myfunc(**possible_param)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/470054.html
下一篇:從父子關系創建選單路徑