Alexander Hultnér
Lead Product Developer at Cetrez
Python Data Classes
A hybrid company within tech and business development.
Python Data Classes
Python Data Classes
Alexander Hultnér
Python Data Classes
Alexander Hultnér
Python Data Classes in two minutes
Alexander Hultnér
pip install dataclasses
Python Data Classes
Alexander Hultnér
Minimal example
""" A minimal basic example """
from dataclasses import dataclass
from datetime import datetime
# A PyCon Example class
@dataclass
class PyCon:
    location: str
    date: datetime
    year: int = 2018  # Default year
# You get init, repr & eq for free out of the box
# More available through decorator paramsAlexander Hultnér
Extended example
@dataclass
class PyCon:
    location: str
    # Can be passed as a str or datetime
    date: Union[datetime, str]
    
    # Add a factory for this year
    year: int = field(
        default_factory=lambda: datetime.now().year
    )
    
    # post init runs after __init__ finishes
    def __post_init__(self):
        
        if isinstance(self.date, str):
            # Raises a ValueError if string is invalid isoformat
            self.date = datetime.fromisoformat(self.date)Alexander Hultnér
Python Data Classes
Alexander Hultnér
Python Data Classes
Alexander Hultnér
Python Data Classes
Alexander Hultnér
Will show different different useful examples
in Jupyter Lab.
The notebook, with all code, links, etc from this
presentation will be available on my GitHub (@hultner)
Python Data Classes
Alexander Hultnér
Go out and use data classes!
And links!
Python Data Classes