0

In Python, I often find myself needing an something like NamedTuple (immutable, typed), but with an overrideable constructor and extendability.

The (Python 3.6+) Syntax

class MyThing(NamedTuple):
    thing1: int
    thing2: float

Is nice, but it:

  1. Doesn't let you override the __new__ constructor, which is useful for parameter checking and type coercion.
  2. Cannot be extended in a logical way: i.e.

    class MySpecificThing(MyThing):
        thing3: str
    

    Cannot be constructed with

    obj = MySpecificThing(thing1=2, thing2=2.5, thing3='aaa')
    

    (You get TypeError: __new__() got an unexpected keyword argument 'thing3')

Does anybody know of a data structure that has all of these nice properties (immutability, typed fields, extendability, and customizable construction)?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Peter
  • 12,274
  • 9
  • 71
  • 86
  • 1
    [You can use Data classes.](https://www.python.org/dev/peps/pep-0557/) – Mazdak Jun 21 '18 at 08:21
  • @Kasramvd you should make that an answer (but extend it with an example or two) – Duncan Jun 21 '18 at 08:23
  • 1
    I already have a related answer here https://stackoverflow.com/a/49874728/2867928, but I think I'm lazier than posting one. Also I think OP can find necessary things in documentation. – Mazdak Jun 21 '18 at 08:25
  • Ah, thanks. Those look great. For others reading this and not yet using Python3.7, there appears to be a backport available here: https://github.com/ericvsmith/dataclasses – Peter Jun 21 '18 at 09:51

0 Answers0