Python etc / attrs


A lot of Python classes start with a similar boilerplate: straightforward constructor, trivial repr and stuff like that:

class Server:
    def __init__(self, ip, version=4):
        self.ip = ip
        self._version = version

    def __repr__(self):
        return '{klass}("{ip}", {version})'.format(

One way to deal with it is to use popular attrs package, which does a lot of default things automatically driving by few declarations:

class Server:
    ip = attr.ib()
    _version = attr.ib(default=4)

server = Server(ip='', version=4)

It not only creates initializer and repr for you but a complete set of comparison methods as well.

That said, there is the upcoming change in Python 3.7, that brings us data classes, the standard library addition that should solve the same problem (and more). It uses the variable annotations, another comparably new Python feature. Here is an example:

class InventoryItem:
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand