dataclasses (Python 3.6 Backport)

0.8 · maintenance · verified Thu Apr 09

The `dataclasses` library is a backport of the standard library `dataclasses` module, designed specifically for Python 3.6. It provides the `@dataclass` decorator and related utilities, enabling simpler creation of data-holding classes without boilerplate. Its current version is 0.8. As it targets a specific, older Python version, its release cadence is stable and infrequent, with no new feature development anticipated.

Warnings

Install

Imports

Quickstart

Define a simple data class using the `@dataclass` decorator. Note the `from __future__ import annotations` which is highly recommended for type hints in Python 3.6 to handle forward references and complex types gracefully. Mutable default values for fields should use `default_factory`.

from __future__ import annotations # Recommended for Python 3.6 type hints
from dataclasses import dataclass, field

@dataclass
class User:
    id: int
    name: str = "Guest"
    email: str | None = None  # Using Union syntax (PEP 604) or typing.Optional
    tags: list[str] = field(default_factory=list)

# Example usage
user1 = User(id=1, name="Alice")
user2 = User(id=2, email="bob@example.com")

print(user1)
print(user2)

assert user1.name == "Alice"
assert user2.tags == []

view raw JSON →