Skip to main content

PEP-557 compatible dataclasses backport for Python 2.7+

Project description

py2dataclasses

This project is a PEP-557 compatible dataclass implementation for Python 2.7.

Usage

  1. pip install py2dataclasses
  2.  # We have to use `field` syntax because Python 2 doesn't support type annotations.
     from dataclasses import dataclass, field
     
     @dataclass
     class Point(object):
         x = field(int)
         y = field(int)
     
     p = Point(3, 4)
     print(p)        # Point(x=3, y=4)
     print(p.x)      # 3
     print(p == Point(3, 4))  # True
    
Big fat (working!) example
from __future__ import print_function
from dataclasses import (dataclass, field, fields, asdict, astuple,
                         replace, make_dataclass, is_dataclass, InitVar,)
from typing import ClassVar

@dataclass
class Address(object):
    street = field(str)
    city = field(str)
    zipcode = field(str, default="00000")

@dataclass
class Person(object):
    company = field(ClassVar[str], "Acme Corp")
    name = field(str)
    age = field(int)
    address = field(Address)
    salary_multiplier = field(InitVar[float], default=1.0)
    salary = field(int, default=50000)

    def __post_init__(self, salary_multiplier):
        self.salary = int(self.salary * salary_multiplier)

addr = Address("123 Main St", "Anytown")
person = Person("Alice", 30, addr, salary_multiplier=1.5)

print(person)
# Person(name='Alice', age=30, address=Address(...), salary=75000)

print(asdict(person))
# {'name': 'Alice', 'age': 30, 'address': {...}, 'salary': 75000}

person2 = replace(person, age=31)
assert person2.age == 31
assert person.age == 30

assert Person.company == "Acme Corp"
assert is_dataclass(person)

More examples here.

loads() / dumps() use json by default and can use any serializer module with loads() / dumps() functions:

import msgpack
from dataclasses import dumps, loads

payload = dumps(Point(3, 4), serializer=msgpack, use_bin_type=True)
point = loads(Point, payload, serializer=msgpack, raw=False)

load() / loads() reject unknown input keys by default. Pass unknown=EXCLUDE to ignore unknown, ClassVar, or init=False input keys. Scalar fields use marshmallow-style coercion by default; pass strict_types=True to require values to already match their annotated runtime types. dump() / dumps() serialize the current dataclass instance and do not run load-time validation.

Dataclass helper caches are enabled by default with @dataclass(cache=True). The repeated load() / loads() / validate() / validates() / dump() / dumps() path reuses resolved field metadata for better performance. Classes that intentionally update field definitions, field types, __annotations__, __dataclass_fields__, or ClassVar / init=False metadata at runtime can opt out per class with @dataclass(cache=False) or make_dataclass(..., cache=False).

Development

Several testenvs provided to run tests in different configurations:

  • test_ported_on_portedlib_py27
    • runs ported to py2.7 tests on backported dataclasses (runs with py27)

  • test_ported_on_portedlib
    • runs ported to py2.7 tests on backported dataclasses (runs with py3)

  • test_native_on_nativelib
    • runs native python 3.14 tests on stdlib dataclasses (runs with py3)

  • test_native_on_portedlib
    • runs native python 3.14 tests on backported dataclasses (runs with py3)

  • test_ported_on_nativelib
    • runs ported to py2.7 tests on stdlib dataclasses (runs with py3)

Fixtures

  • tests._fixtures_py314 dir contains original python 3.14 tests for the dataclasses lib. Test themselves are in __init__.py
  • tests._fixtures_py27 dir contains tests ported from python 3.14 to python 2.7 as closely as possible. Test themselves are in __init__.py

Helpers

  • tests._xmlrunner is a helper to run coverage alongside tests
  • tests._xmlprocessor is a helper for the CI

Adapters

  • tests._fixtures_compat_backport_to_stdlib
  • tests._fixtures_compat_stdlib_to_backport

Source

  • dataclasses
  • _py2dataclasses

⚠ WARNING

  • Please, do not use Python 2.7 in 2026

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py2dataclasses-3.14.115.tar.gz (130.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

py2dataclasses-3.14.115-py3-none-any.whl (44.4 kB view details)

Uploaded Python 3

File details

Details for the file py2dataclasses-3.14.115.tar.gz.

File metadata

  • Download URL: py2dataclasses-3.14.115.tar.gz
  • Upload date:
  • Size: 130.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for py2dataclasses-3.14.115.tar.gz
Algorithm Hash digest
SHA256 bb7326bb92779ece10d833d7a5b68cc0e64eb012c07029b96c98144dccf88fd5
MD5 969512f01a7d61c3f54a31205b2d8979
BLAKE2b-256 8be168d3cadb3d77fe0898237281a02662348884f0e135d01ea35b714abcc3e8

See more details on using hashes here.

File details

Details for the file py2dataclasses-3.14.115-py3-none-any.whl.

File metadata

File hashes

Hashes for py2dataclasses-3.14.115-py3-none-any.whl
Algorithm Hash digest
SHA256 c8eec42b867eaec57792a25558f760ac9f603d5454845a25cf91c7d5e403a2ba
MD5 8a983a97369628a5a0a647be6b3b6d9c
BLAKE2b-256 72e0f46823b4d6cf0ddc99df5f3f75846a2ea20f6356e44c029e377115d4e7e5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page