typeddfs._mixins._dataclass_mixin

Dataclass mixin.

Module Contents

class typeddfs._mixins._dataclass_mixin.TypedDfDataclass

Just a dataclass for TypedDfs. Contains get_df_type() to point to the original DataFrame.

get_as_dict(self) Mapping[str, Any]

Returns a mapping from the dataclass field name to the value.

abstract classmethod get_df_type(cls) Type[TypedDf]

Returns the original DataFrame type.

classmethod get_fields(cls) Sequence[dataclasses.Field]

Returns the fields of this dataclass.

class typeddfs._mixins._dataclass_mixin._DataclassMixin
classmethod _create_dataclass(cls, fields: Sequence[Tuple[str, Type[Any]]]) Type[TypedDfDataclass]
classmethod create_dataclass(cls, reserved: bool = True) Type[TypedDfDataclass]

Creates a best-effort immutable dataclass for this type. The fields will depend on the columns and index levels present in get_typing(). The type of each field will correspond to the specified dtype (typeddfs.df_typing.DfTyping.auto_dtypes()), falling back to Any if none is specified.

Note

If this type can support additional columns (typeddfs.df_typing.DfTyping.is_strict() is the default, False), the dataclass will not be able to support extra fields. For most cases, typeddfs.abs_dfs.AbsDf.to_dataclass_instances() is better.

Parameters

reserved – Include reserved columns and index levels

Returns

A subclass of typeddfs.abs_dfs.TypedDfDataclass

classmethod from_dataclass_instances(cls, instances: Sequence[TypedDfDataclass]) __qualname__

Creates a new instance of this DataFrame type from dataclass instances. This mostly delegates to pd.DataFrame.__init__, calling cls.of(instances). It is provided for consistency with to_dataclass_instances().

Parameters

instances – A sequence of dataclass instances. Although typed as typeddfs.abs_dfs.TypedDfDataclass, any type created by Python’s dataclass module should work.

Returns

A new instance of this type

to_dataclass_instances(self) Sequence[TypedDfDataclass]

Creates a dataclass from this DataFrame and returns instances. Also see from_dataclass_instances().

Note

Dataclass elements are equal if fields and values match, even if they are of different types. This was done by overriding __eq__ to enable comparing results from separate calls to this method. Specifically, typeddfs.abs_dfs.TypedDfDataclass.get_as_dict() must return True.

Caution

Fields cannot be included if columns are not present. If self.get_typing().is_strict is False, then the dataclass created by two different DataFrames of type self.__class__ may have different fields.

Caution

A new dataclass is created per call, so df.to_dataclass_instances()[0] is not df.to_dataclass_instances()[0].