7

I am trying to learn more about Python - I am using 3.6.3 currently.

What is the best practice for argument validation/parsing when using kwargs?

Or, what is the best practice for argument validation/parsing without kwargs?

class foo:
  def __init__(self, **kwargs):
    if 'a' in kwargs:
      self.a = kwargs['a']
    else:
      self.a = 0

class bar(foo):
  def __init__(self, **kwargs):
    super().__init__()
    if 'x' in kwargs:
      self.x = kwargs['x']
    else:
      self.x = 23

# b and y are undefined, but my classes use kwargs - what is the best practice for validating / parsing dynamic arguments?
test = bar(b=1,y=24)
0

2 Answers 2

6

You can pass a default value to get() for keys that are not in the kwargs dictionary:

def __init__(self, **kwargs):
    self.a = kwargs.get("a", 0)
    self.x = kwargs.get("x", 23)
    # etc.

Alternatively if you want any value in kwargs to be set as an instance variable of your class, you could do:

def __init__(self, **kwargs):
    for k, v in kwargs.items():
        self.__setattr__(k, v)
2
class Foo:
   def __init__(self,a=0):
       self.a = a

class Bar(Foo):
    def __init__(self,b=21,**kwargs):
        self.b = b  # accept whatever you want for this child
        Foo.__init__(self,**kwargs) # pass remaining kwargs down the line

does exactly what your Foo class does and is much more clear

most problems with using kwargs come from the fact that its not at all self documenting ... I have no idea what arguments can and should be supplied for neither Foo or Bar where as explicitly declared arguments with default values make it very clear what options are available to pass into the functions

3
  • 1
    I understand that, and that is exactly my question - is there a best practice way for attempting to validate arguments when using kwargs, or the best practice is just to create more well defined and less dynamic classes or child classes?
    – johnnygear
    Oct 13, 2017 at 1:10
  • 1
    The more common case where **kwargs is used, to my knowledge, is when either (a) the class you are inheriting is one you don't own or control, or (b) when you are not in fact inheriting the class. pandas.read_hdf offers a nice example: it is using pytables, which incorporates HDF5, and (presumably) with so many potential changes out of its control, that read_hdf method has its own parameters, followed by **kwargs, which is just passed up the stream to be used by pytables. Jul 4, 2018 at 0:05
  • this is definately true ... but is not counter to my point about the problems with kwargs either Jul 4, 2018 at 4:08

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.