Package: dataclassy
dataclassydataclassyis a reimplementation of data classes in Python - an alternative to the built-indataclasses modulethat avoids many ofitscommonpitfalls. dataclassy is designed to be more flexible, less verbose, and more powerful than dataclasses, while retaining a familiar interface.In short, dataclassy is a library for moving data around your Python programs that's optimised for speed, simplicity and developer happiness.fromdataclassyimportdataclassfromtypingimportDict@dataclassclassPet:name:strspecies:strfluffy:boolfoods:Dict[str,int]={}Why use dataclassy?This section describes various motivations for usingdataclassyoverdataclasses.Backwards compatibilitydataclassy implements the decorator options of the latest version of dataclasses, plus its own, such that they are compatible back to Python 3.6. It istested againstCPython 3.6 through 3.11andPyPy 3.6 through 3.9.Upgrade your data classesnew decorator optionsslotsgenerates__slots__to reduce memory footprint and improve attribute lookup performancekwargsappends**kwargsto__init__'s parameter list to consume unexpected argumentsiterallows class instances to be destructured, like named tupleshide_internalsautomatically hides private fields from__repr__and excludes them from comparison and iteration@dataclassusage and options are inherited (subclasses do not have to reuse the decorator)fields can be in any order - fields with defaults arereordered- making inheritance feasiblemutable default values (list,set,dictand more) areautomatically copiedupon initialisationnew functions:is_dataclass_instanceandvaluesAdditionally, dataclassyimplements all the decorator options and functions of dataclassesis tiny (~160 LOC; less than 25% the size of dataclasses)has no external dependencies, and no stdlib imports other thantypes,typingandreprlibisfast, matching dataclasses' performance whenslots=Falseand significantly exceeding it whenslots=Truesupports multiple inheritance and custom metaclassescomes withsupport for mypyOther differencesdataclassy's API is strongly influenced by dataclasses', but with a focus on minimalism and elegance.there's nofieldorField. UseHashed,Internalorfactoryto replicate its functionsthere's noInitVar. Simply add arguments to__post_init__there's no need forClassVar. Simply omit the field's type hint to ignore itAlso considerattrsif you need complex validation and type conversionspydanticif you need strict type checkingUsageInstallationInstall the latest release fromPyPIwith pip:pip install dataclassyOr install the latest development version straight from this repository:pip install https://github.com/biqqles/dataclassy/archive/master.zip -UMigrationdataclassy's API is broadly similar to dataclasses. If you simply use the decorator and other functions, it is possible to instantly migrate from dataclasses to dataclassy by simply changingfromdataclassesimport*tofromdataclassyimport*Otherwise, you will have to make a couple of easy refactorings (that should leave you with cleaner code!). Consult the table underDifferencesor skip ahead toExamplesto see dataclassy in action.Similaritiesdataclassy'sdataclassdecorator takes all of the same arguments as dataclasses', plus its own, and should therefore be a drop-in replacement.dataclassy also implements all dataclasses'functions:is_dataclass,fields,replace,make_dataclass,asdictandastuple(the last two are aliased fromas_dictandas_tuplerespectively), and they should work as you expect.DifferencesAlthough dataclassy's API is similar to dataclasses',compatibility with it is not a goal(this is similar to the relationship between Crystal and Ruby).dataclassy has several important differences from dataclasses, mainly reflective of its minimalistic style and implementation. These differences are enumerated below and fully expanded on in the next section.dataclassesdataclassyinit-only variablesfields with typeInitVararguments to__post_init__class variablesfields with typeClassVarfields without type annotationmutable defaultsa: Dict = field(default_factory=dict)a: Dict = {}dynamic defaultsb: MyClass = field(default_factory=MyClass)b: MyClass = factory(MyClass)field excluded fromreprc: int = field(repr=False)Internaltype wrapper or_name"late init" fieldd: int = field(init=False)d: int = Noneabstract data classclass Foo(ABC):class Foo(metaclass=ABCMeta):There are a couple of minor differences, too:fieldsreturnsDict[str, Type]instead ofDict[Field, Type]and has an additional parameter which filters internal fieldsAttempting to modify a frozen instance raisesAttributeErrorwith an explanation rather thanFrozenInstanceErrorFinally, there are some quality of life improvements that, while not being directly implicated in migration, will allow you to make your code cleaner:@dataclassdoes not need to be applied to every subclass - its behaviour and options are inheritedUnlike dataclasses, fields with defaults do not need to follow those without them. This is particularly useful when working with subclasses, which is almost impossible with dataclassesdataclassy adds aDataClasstype annotation to represent variables that should be generic data class instancesdataclassy has theis_dataclass_instancesuggested as arecipefor dataclasses built-inThe generated comparison methods (whenorder=True) are compatible with supertypes and subtypes of the class. This means that heterogeneous collections of instances with the same superclass can be sortedIt is also worth noting that internally, dataclasses and dataclassy work in different ways. You can think of dataclassy asturning your class into a different type of thing(indeed, it uses a metaclass) and dataclasses as merelyadding things to your class(it does not).ExamplesThe basicsTo define a data class, simply apply the@dataclassdecorator to a class definition (see above).Without arguments to the decorator, the resulting class will behave very similarly to its equivalent from the built-in module. However, dataclassy's decorator has some additional options over dataclasses', and it is also inherited so that subclasses of data classes are automatically data classes too.The decorator generates various methods for the class. Which ones exactly depend on the options to the decorator. For example,@dataclass(repr=False)will prevent a__repr__method from being generated.@dataclassis equivalent to using the decorator with default parameters (i.e.@dataclassand@dataclass()are equivalent). Options to the decorator are detailed fully in thenext section.Class variablesYou can exclude a class attribute from dataclassy's mechanisms entirely by simply defining it without a type annotation. This can be used for class variables and constants.Parameter reorderingdataclassy modifies the order of fields when converting them into parameters for the generated__init__. Specifically, fields with default values always follow those without them. This stems from Python's requirement thatparameterswith default arguments follow those without them. Conceptually, you can think of the process to generate the parameter list like this:dataclassy takes the fields in definition orderit splits them into two lists, the first being fields without default values and the second being fields with themit appends the second list to the firstThis simple design decision prevents the dreadedTypeError: non-default argument '...' follows default argumenterror that anyone who has tried to do serious inheritance using dataclasses will know well.You can verify the signature of the generated initialiser for any class usingsignaturefrom theinspectmodule. For example, using the definition linked to above,inspect.signature(Pet)will return(name: str, species: str, fluffy: bool, foods: Dict[str, int] = {})).If we then decided to subclassPetto add a new field,hungry:@dataclassclassHungryPet(Pet):hungry:boolYou will see thatinspect.signature(HungryPet)returns(name: str, species: str, fluffy: bool, hungry: bool, foods: Dict[str, int] = {}).InheritanceUnlike dataclasses, dataclassy's decorator only needs to be applied once, and all subclasses will become data classes with the same options as the parent class. The decorator can still be reapplied to subclasses in order to apply new parameters.To change the type, or to add or change the default value of a field in a subclass, simply redeclare it in the subclass.Post-initialisation processingIf an initialiser is requested (init=True), dataclassy automatically sets the attributes of the class upon initialisation. You can define code that should run after this happens - this is calledpost-init processing.The method that contains this logic should be called__post_init__. Like with dataclasses, ifinit=Falseor the class has no fields,__post_init__will not be called.@dataclassclassCustomInit:a:intb:intdef__post_init__(self):self.c=self.a/self.bIn this example, when the class is instantiated withCustomInit(1, 2), the fieldcis calculated as0.5.Like with any function, your__post_init__can also take parameters which exist only in the context of__post_init__. These can be used for arguments to the class that you do not want to store as fields. A parameter cannot have the name of a class field; this is to prevent ambiguity.Default valuesDefault values for fields work exactly as default arguments to functions (and in fact this is how they are implemented), with one difference: for copyable defaults, a copy is automatically created for each class instance. This means that a new copy of thelistfieldfoodsinPetabove will be created each time it is instantiated, so that appending to that attribute in one instance will not affect other instances. A "copyable default" is defined as any object implementing acopymethod, which includes all the built-in mutable collections (includingdefaultdict).If you want to create new instances of objects which do not have acopymethod, use thefactoryfunction. This function takes any zero-argument callable. When the class is instantiated, this callable is executed to produce a default value for the field:classMyClass:pass@dataclassclassCustomDefault:m:MyClass=factory(MyClass)CustomDefault()# CustomDefault(m=<__main__.MyClass object at 0x7f8b156feb50>)CustomDefault()# CustomDefault(m=<__main__.MyClass object at 0x7f8b156fc7d0>)APIDecorator@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, hide_internals=True, iter=False, kwargs=False, slots=False, meta=DataClassMeta)The decorator used to signify that a class definition should become a data class. The decorator returns a new data class with generated methods as detailed below. If the class already defines a particular method, it will not be replaced with a generated one.Without arguments, its behaviour is, superficially, almost identical to its equivalent in the built-in module. However, dataclassy's decorator only needs to be applied once, and all subclasses will become data classes with the same parameters. The decorator can still be reapplied to subclasses in order to change parameters.A data class' fields are defined using Python's type annotations syntax. To change the type or default value of a field in a subclass, simply redeclare it.This decorator takes advantage of two equally important features added in Python 3.6:variable annotationsanddictionaries being ordered. (The latter is technically animplementation detailof Python 3.6, only becoming standardised in Python 3.7, but is the case for all current implementations of Python 3.6, i.e. CPython and PyPy.)Decorator optionsThe term "field", as used in this section, refers to a class-level variable with a type annotation. For more information, see the documentation forfields()below.initIf true (the default), generate an__init__method that has as parameters all fields up its inheritance chain. These are ordered in definition order, with all fields with default values placed towards the end, following all fields without them. The method initialises the class by applying these parameters to the class as attributes. If defined, it will also call__post_init__with any remaining arguments.This ordering is an important distinction from dataclasses, where all fields are simply ordered in definition order, and is what allows dataclassy's data classes to be far more flexible in terms of inheritance.A shallow copy will be created for mutable arguments (defined as those defining acopymethod). This means that default field values that are mutable (e.g. a list) will not be mutated between instances.reprIf true (the default), generate a__repr__method that displays all fields (or ifhide_internalsis true, all fields excludinginternalones) of the data class instance and their values.eqIf true (the default), generate an__eq__method that compares this data class to another of the same type as if they were tuples created byas_tuple, excludinginternal fieldsifhide_internalsis true.orderIf true, a__lt__method is generated, making the classorderable. Ifeqis also true, all other comparison methods are also generated. These methods compare this data class to another of the same type (or a subclass) as if they were tuples created byas_tuple, excludinginternal fieldsifhide_internalsis true. The normal rules oflexicographical comparisonapply.unsafe_hashIf true, force the generation of a__hash__method that attempts to hash the class as if it were a tuple of its hashable fields. Ifunsafe_hashis false,__hash__will only be generated ifeqandfrozenare both true.match_argsIf true (the default), generate a__match_args__attribute that enables structural pattern matching on Python 3.10+.kw_onlyIf true, all parameters to the generated__init__are marked askeyword-only. This includes arguments passed through to__post_init__.frozenIf true, instances are nominally immutable: fields cannot be overwritten or deleted after initialisation in__init__. Attempting to do so will raise anAttributeError.Warning: incurs a significant initialisation performance penalty.hide_internalsIf true (the default),internal fieldsare not included in the generated__repr__, comparison functions (__eq__,__lt__, etc.), or__iter__.iterIf true, generate an__iter__method that returns the values of the class's fields, in order of definition, noting thatinternal fieldsare excluded whenhide_internalsis true. This can be used to destructure a data class instance, as with a Scalacase classor a Pythonnamedtuple.kwargsIf true, add**kwargsto the end of the parameter list for__init__. This simplifies data class instantiation from dictionaries that may have keys in addition to the fields of the data class (i.e.SomeDataClass(**some_dict)).slotsIf true, generate a__slots__attribute for the class. This reduces the memory footprint of instances and attribute lookup overhead. However,__slots__come with a fewrestrictions(for example, multiple inheritance becomes tricky) that you should be aware of.metaSet this parameter to use a metaclass other than dataclassy's own. This metaclass must subclassdataclassy.dataclass.DataClassMeta.DataClassMetais best considered less stable than the parts of the library available in the root namespace. Only use a custom metaclass if absolutely necessary.Functionsfactory(producer)Takes a zero-argument callable and creates afactorythat executes this callable to generate a default value for the field at class initialisation time.is_dataclass(obj)Returns True ifobjis a data class as implemented in this module.is_dataclass_instance(obj)Returns True ifobjis an instance of a data class as implemented in this module.fields(dataclass, internals=False)Return a dict ofdataclass's fields and their types.internalsselects whether to include internal fields.dataclasscan be either a data class or an instance of a data class.A field is defined as a class-level variable with atype annotation. Variables defined in the class without type annotations are completely excluded from dataclassy's consideration. Class variables and constants can therefore be indicated by the absence of type annotations.values(dataclass, internals=False)Return a dict ofdataclass's fields and their values.internalsselects whether to include internal fields.dataclassmust be an instance of a data class.as_dict(dataclass dict_factory=dict)Recursively create a dict of a data class instance's fields and their values.This function is recursively called on data classes, named tuples and iterables.as_tuple(dataclass)Recursively create a tuple of the values of a data class instance's fields, in definition order.This function is recursively called on data classes, named tuples and iterables.make_dataclass(name, fields, defaults, bases=(), **options)Dynamically create a data class with namename, fieldsfields, default field valuesdefaultsand inheriting frombases.replace(dataclass, **changes)Return a new copy ofdataclasswith field values replaced as specified inchanges.Type hintsInternalTheInternaltype wrapper marks a field as being "internal" to the data class. Fields which begin with the"internal use"idiomatic indicator_or theprivate fieldinterpreter indicator__are automatically treated as internal fields.  TheInternaltype wrapper therefore serves as an alternative method of indicating that a field is internal for situations where you are unable to name your fields in this way.HashedUseHashedto wrap the type annotations of fields that you want to be included in a data class'__hash__. The value hashed by__hash__consists of a tuple of the instance's type followed by any fields marked asHashed.DataClassUse this type hint to indicate that a variable, parameter or field should be a generic data class instance. For example, dataclassy uses these in the signatures ofas_dict,as_tupleandvaluesto show that these functions should be called on data class instances.Mypy supportIn order to use dataclassy in projects with mypy, you will need to use the mypy plugin. You can create amypy.inior.mypy.inifor such projects with the following content:[mypy]plugins=dataclassy.mypy