I have some existing Python 3.6 code that I\'d like to move to Python 3.7 dataclasses. I have __init__
methods with nice docstring documentation, specifying the
A major advantage of dataclasses is that they are self-documenting. Assuming the reader of your code knows how dataclasses work (and your attributes are appropriately named), the type-annotated class attributes should be excellent documentation of the constructor. See this example from the official dataclass docs:
@dataclass
class InventoryItem:
'''Class for keeping track of an item in inventory.'''
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
If you don't expect that readers of your code would know how dataclasses work then you might want to reconsider using them or adding an explanation or link to the docs in an inline comment after the @dataclass
decorator. If you really need a docstring for a dataclass, I'd recommend putting the constructor docstring within the class docstring. For the example above:
'''Class for keeping track of an item in inventory.
Constructor arguments:
:param name: name of the item
:param unit_price: price in USD per unit of the item
:param quantity_on_hand: number of units currently available
'''