How to avoid repetitive code when defining a new type in python

777 views python

I wonder if there is a better solution to define a new type in python.

I am writing the init method of a new class in this way:

class MyType (Base):

  def __init__(self, **kwargs):
    self.a1 = kwargs['a1']
    self.a2 = kwargs['a2']
    self.a3 = kwargs['a3']
    self.a4 = kwargs['a4']
    self.a5 = kwargs['a5']

but I would like to write a compact coding style like that:

class MyType (Base):

   __fields__ = ['a1', 'a2', 'a3', ...]

Thanks, Frederick

answered question

just do self.__dict__.update(**kwargs).

Why don't you just store the **kwargs directly in an inner dictionary and access it that way when needed given that you obviously don't care about defining an interface?

2 Answers


You can just update the instance dict in __init__.

>>> class MyType:
...:    def __init__(self, **kwargs):
...:        vars(self).update(kwargs)
>>> m = MyType(a1=1, a2=2, a3=3)
>>> vars(m)
>>> {'a1': 1, 'a2': 2, 'a3': 3}
>>> m.a1, m.a2, m.a3
>>> (1, 2, 3)

posted this

Have a look at python3.7 data classes.

Quote from there:

class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

Will add, among other things, a __init__() that looks like:

def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0): = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand

posted this

Have an answer?


Please login first before posting an answer.