Reputation: 594
I want to make a user-level method inside a class, in which arguments can be passed through several variation of a keyword. To do so, I set up a list of allowed variations for each keyword argument and check for each keyword in each of these lists. e.g. :
def some_function(self, **kwargs):
"""
this function does something with a and b as keyword args
"""
dict_allowed_a = ['a_variation1','a_variation2',...]
dict_allowed_b = ['b_variation1','b_variation2',...]
for arg_str in kwargs():
if arg_str in dict_allowed_a:
local_a = kwargs[arg_str]
if arg_str in dict_allowed_b:
local_b = kwargs[arg_str]
else:
print('Invalid keyword', file=sys.stderr)
raise ValueError
return self._private_method(local_a, local_b)
I have 3 questions, from more specific to less specific :
Upvotes: 1
Views: 3862
Reputation: 1048
Please notice that you have to deal with strange situations, such as
a_variation1
and a_variation2
I would use something like
local_a = ([kwargs[x] for x in kwargs.keys() if x in dict_allowed_a] + [None])[0]
local_b = ([kwargs[x] for x in kwargs.keys() if x in dict_allowed_b] + [None])[0]
Please notice that [0]
will extract the first value only, this handles case 1.
[None]
is something like a default, it's used in case 2.
Upvotes: 1