Reputation: 5322
I would like to return an unpacked dictionary based on some condition:
def process(batch, cond):
if(cond):
return **batch
else
return batch
input = process(batch, cond)
output = model(input)
However, I get a SyntaxError: invalid syntax
because of the return **batch
line.
Upvotes: 0
Views: 137
Reputation: 11613
If I understand correctly, you could achieve what you want like this:
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
Upvotes: 1
Reputation: 11496
You can't. You need to extract your unpack logic to outside of process
:
def process(batch):
return batch
input = process(batch)
if cond:
output = model(**input)
else:
output = model(input)
If you really need process
, also pass model
to it:
def process(batch, model, cond):
input = process(batch)
if cond:
return model(**input)
return model(input)
output = process(batch, model, cond)
Upvotes: 2