Search code examples
pythonclassoopkeyword-argument

When to use keyword arguments for class initialisation?


When creating my own classes I can't work out when I should or shouldn't use keyword arguments.

Are there any specific circumstances or general rules of thumb on this?

As far as I can tell:

Pros:

  1. Explicit definition so makes it harder for variables to get put in the wrong order
  2. Makes the code more readable

Cons:

  1. By having a keyword argument you need to also supply a default value, which means instances can be initialised without any arguments being supplied.

Please see below MyClassA and MyClassB which illustrate these two points:

class MyClassA():

    def __init__(self,name,city):

        self.name = name
        self.city = city

x = MyClassA('Andy','New York')



class MyClassB():

    def __init__(self,name=None,city=None):

        self.name = name
        self.city = city

 y = MyClassB(city='New York',name='Andy')

Solution

  • Actually, in both cases, you can pass arguments as keyword arguments:

    x = MyClassA(city='New York', name='Andy')
    

    would also work. And this:

    x = MyClassA(name='Andy', city='New York')
    

    would also work.

    The general rule of thumb (IMHO): if it is obvious at the call site what are the arguments - no need in keywords, otherwise - Explicit is better than implicit.

    And just FYI, you can force usage of keyword args like so:

    def fun(positional_arg1, *, keyword_only_arg1, keyword_only_arg2): ...
    

    which means that you can't call fun with positional arguments:

    >>> fun(1, 2, 3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: fun() takes 1 positional argument but 3 were given
    

    and you have to provide all arguments:

    >>> fun(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: fun() missing 2 required keyword-only arguments: 
    'keyword_only_arg1' and 'keyword_only_arg2'
    

    So the only way to call fun is:

    fun(1, keyword_only_arg1=1, keyword_only_arg2=3)