MaximGi
MaximGi

Reputation: 594

Managing duplicate keyword arguments

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 :

  1. How can I check if someone passed several variations of one argument, which has to raise an exception.
  2. Am I doing this properly ?
  3. Should I even do this, trying to manage variable inputs ?

Upvotes: 1

Views: 3862

Answers (1)

luca.vercelli
luca.vercelli

Reputation: 1048

Please notice that you have to deal with strange situations, such as

  1. The user specify both a_variation1 and a_variation2
  2. The user does not specify any of them

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

Related Questions