Data Classes
In Python 3.6 and beyond

PyCon SE 2018, Stockholm, Sweden

Alexander Hultnér

Alexander Hultnér

Lead Product Developer at Cetrez

Python Data Classes

Cetrez

A hybrid company within tech and business development.

cetrez.com

blog.cetrez.com

  • Build software system for large international brands
  • Our HQ in Gothenburg is a Normandie inspired castle
  • We host Hackathons, Meetups, etc
  • We love Python

Python Data Classes

Outline

 Python Data Classes 

Alexander Hultnér

  • Why
  • Cheatsheet summary, Data Classes in two minutes
  • History
  • Using Data Classes
  • Examples
  • Utility Classes
  • JSON-handling
  • Interactive Jupyter session, showing real usecases
  • Conclusion
  • Questions & links

Why?

 Python Data Classes 

Alexander Hultnér

  • Simplifies Python Classes
    • Less boilerplate => less bugs
  • ​Built on top of previous experience
    • ​not bound to legacy
  • ​In standard Python
    • ​Libraries and ecosystem likely to grow
  • ​Extensible and customisable

 

Cheatsheet

 Python Data Classes in two minutes

Alexander Hultnér

  • Coming in Python 3.7
  • Usable  in 3.6
    • pip install dataclasses
    • requires type annotations and sorted dict
  • Native alternative to attrs
  • Learned from NamedTuples

History

 Python Data Classes 

Alexander Hultnér

  • NamedTuple
  • attrs
    • Similar libraries
  • ORM-libraries such as SQLAlchemy
  • PEP 557-backport

 

Data class

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 params

Alexander Hultnér

Data class

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

Utility functions

 Python Data Classes 

Alexander Hultnér

  • dataclass-module
    • ​asdict
    • astuple
    • make_dataclass
    • is_dataclass
    • replace
    • and more
  • Handy attributes on the class
    • __annotations__
    • __dataclass_params__
    • __dataclass_fields__

JSON-Conversion

 Python Data Classes 

Alexander Hultnér

  • asdict
    • ​Passed to json.dumps
  • ​Create instance from json
    • ​Expand kwargs (**)
  • Custom JSONEncode
    • ​Can be made in a few lines of code
  • ​Will show more details in Jupyter

Interactive Jupyter session

 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)

Conclusion

 Python Data Classes 

Alexander Hultnér

  • Great code generator
  • Usable in 3.6 onward
  • Native i 3.7
  • Versatile

Go out and use data classes!

Questions?

And links!

Python Data Classes

Alexander Hultnér

Data Classes, in Python 3.6 and beyond

By Alexander Hultnér

Data Classes, in Python 3.6 and beyond

Python 3.7 is here and the @dataclass-decorator is a major new feature simplifying class-creation. In this talk, we will learn to use the power of data classes to make our codebases cleaner and leaner in a pythonic way. We will also learn how to use the back-port in Python 3.6 codebases before upgrading.

  • 7,753