My proof-of-concept record type

Back in June, I proposed a struct syntax for Python. I shared the post on Mastodon and got some feedback. Afterwards I thought about what I heard and talked it over with some folks. I've now coded up a proof-of-concept to share to get some more feedback from people to gauge whether people in general like this idea.

And so I created the record-type project on PyPI to share a proof-of-concept of what I think a record type could look like if one was ever added to Python. I shared this on and the feedback was generally positive, so now I'm seeking wider feedback via this blog post. To help show what the record-type does, here's the opening example of the dataclasses documentation converted to use record-type:

from records import record

def InventoryItem(name: str, price: float, *, quantity: int = 0):
    """Class for keeping track of an item in inventory."""

An example of using records.record

As listed in the README of the project's repository, that decorator creates a class with:

  • __slots__ for performance
  • __match_args__ for pattern matching
  • __annotations__ for runtime type annotations
  • __eq__() for equality based on structure (via __slots__), not inheritance
  • __hash__() for hashing
  • __repr__() which is suitable for eval()
  • Immutability

The goal of this design is:

  • Create a simple data type that's easy to explain to beginners
  • Creating the data type itself should be fast (i.e. no concerns over importing a module with a record type)
  • Type annotations are supported, but not required
  • Instances are immutable to make them (potentially) hashable
  • Support Python's entire parameter definition syntax idiomatically for instance instantiation
  • Support structural typing as much as possible (e.g., equality based on object "shape" instead of inheritance)

Now, in all situations where you try to do something that simplifies classes leads to a comparison with dataclasses. Here's the same example, but with dataclasses:

from dataclasses import dataclass, KW_ONLY

@dataclass(frozen=True, slots=True)
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    price: float
    _: KW_ONLY
    quantity: int = 0

The same example using dataclasses.dataclass

Is that worse than the example using record-type? Is any of this compelling enough to turn what record-type proposes into actual syntax? I've had some ask for method support, but I personally like the simplicity of leaning into a data-only approach (see my struct syntax post for more of an explanation). I personally like the structural equality, but I suspect some would be willing to give it up if performance could be improved for equality comparisons.

Anyway, based on the response I may write a PEP to see if there's enough traction to add syntax for this (replies on Mastodon are probably the easiest way to express an opinion).