Reputation: 5648
I have a library, which similar to this sample code:
class PlayBook(object):
def __init__(self, playbook= None, host_list= None, module_path= None,):
print "playbook %s host_list %s module_path %s" % (playbook,host_list,module_path)
I need chose named parameters, that I will pass to function: If I try to do this:
a=1
b=2
c=3
PlayBook(
if a>1:
module_path=a,
playbook=b,
elif b<1:
playbook=b,
else:
host_list=c,
playbook="playbook",
)
I got:
if a>1:
^
SyntaxError: invalid syntax
Question: how to choose named parameters and pass them to function?
PS: I know that I can do like this:
if a>1:
PlayBook(module_path=a,
playbook=b,)
elif b<1:
PlayBook( playbook=b,)
else:
PlayBook( host_list=c,
playbook="playbook",)
Sorry for my English
Upvotes: 1
Views: 53
Reputation: 46533
I'd collect the parameters into dict
and unpack it afterwards:
if a > 1:
params = dict(module_path=a, playbook=b)
elif b < 1:
params = dict(playbook=b)
else:
params = dict(host_list=c, playbook="playbook")
PlayBook(**params) # ** for keyword arguments
Upvotes: 2
Reputation: 599630
No, you can't do that. Move the instantiation into each clause.
if a>1:
PlayBook(
module_path=a,
playbook=b,
)
elif b<1:
PlayBook(
playbook=b,
)
else:
PlayBook(
host_list=c,
playbook="playbook",
)
)
Upvotes: 1