我想根据某些条件返回一个未打包的字典:
def process(batch, cond):
if(cond):
return **batch
else
return batch
input = process(batch, cond)
output = model(input)
然而,我得到一个SyntaxError: invalid syntax
,因为return **batch
线。
你不能。您需要将解包逻辑提取到process
之外:
def process(batch):
return batch
input = process(batch)
if cond:
output = model(**input)
else:
output = model(input)
如果你真的需要process
,也传递model
给它:
def process(batch, model, cond):
input = process(batch)
if cond:
return model(**input)
return model(input)
output = process(batch, model, cond)
如果我理解正确的话,你可以像这样实现你想要的:
def process(batch, cond):
if(cond):
kwargs = batch
else:
kwargs = {'a': batch}
return kwargs
def model(a=0, b=0, c=0):
print(a + b + c)
batch = {'a': 100, 'b': 101, 'c': 102}
cond = True
kwargs = process(batch, cond)
model(**kwargs)
# Output: 303
batch = 100
cond = False
kwargs = process(batch, cond)
model(**kwargs)
# Output: 100