Typing stubs for Python's dataclasses module enabling static type checking
npx @tessl/cli install tessl/pypi-types-dataclasses@0.6.0Type stubs for Python's dataclasses module, providing comprehensive static type checking support for all dataclass functionality. These stubs enable type checkers like mypy, PyCharm, and pytype to accurately analyze code using Python's dataclasses decorator and related utilities.
pip install types-dataclassesfrom dataclasses import dataclass, field, FieldCommon imports for working with dataclasses:
from dataclasses import (
dataclass, field, Field, fields, asdict, astuple,
make_dataclass, replace, is_dataclass, InitVar,
FrozenInstanceError, MISSING
)Python 3.10+ specific:
from dataclasses import KW_ONLYFor type annotations (used internally in stub files):
from builtins import type as Type # Alias to avoid name conflicts
from typing import TypeVar
from typing_extensions import Literal
# Type variables used in dataclasses API
_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True)from dataclasses import dataclass, field
from typing import List, Optional
@dataclass
class Person:
name: str
age: int
email: Optional[str] = None
hobbies: List[str] = field(default_factory=list)
# Create instances
person = Person("Alice", 30, "alice@example.com")
print(person) # Person(name='Alice', age=30, email='alice@example.com', hobbies=[])
# Use utility functions
from dataclasses import asdict, replace
person_dict = asdict(person)
older_person = replace(person, age=31)The main decorator for creating dataclasses with configurable behavior options.
# Python 3.8+ (positional-only cls parameter)
@overload
def dataclass(__cls: type[_T]) -> type[_T]: ...
@overload
def dataclass(__cls: None) -> Callable[[type[_T]], type[_T]]: ...
# Python 3.7 (non-positional-only cls parameter)
@overload
def dataclass(_cls: type[_T]) -> type[_T]: ...
@overload
def dataclass(_cls: None) -> Callable[[type[_T]], type[_T]]: ...
# Python 3.11+ (all options available)
@overload
def dataclass(
*,
init: bool = ...,
repr: bool = ...,
eq: bool = ...,
order: bool = ...,
unsafe_hash: bool = ...,
frozen: bool = ...,
match_args: bool = ...,
kw_only: bool = ...,
slots: bool = ...,
weakref_slot: bool = ...,
) -> Callable[[type[_T]], type[_T]]: ...
# Python 3.10+ (without weakref_slot)
@overload
def dataclass(
*,
init: bool = ...,
repr: bool = ...,
eq: bool = ...,
order: bool = ...,
unsafe_hash: bool = ...,
frozen: bool = ...,
match_args: bool = ...,
kw_only: bool = ...,
slots: bool = ...,
) -> Callable[[type[_T]], type[_T]]: ...
# Python 3.7-3.9 (basic options)
@overload
def dataclass(
*,
init: bool = ...,
repr: bool = ...,
eq: bool = ...,
order: bool = ...,
unsafe_hash: bool = ...,
frozen: bool = ...,
) -> Callable[[type[_T]], type[_T]]: ...Parameters:
init: Generate __init__ method (default: True)repr: Generate __repr__ method (default: True)eq: Generate __eq__ method (default: True)order: Generate ordering methods (__lt__, __le__, __gt__, __ge__) (default: False)unsafe_hash: Generate __hash__ method (default: False)frozen: Make instances immutable (default: False)match_args: Generate __match_args__ for pattern matching (3.10+, default: True)kw_only: Make all fields keyword-only (3.10+, default: False)slots: Generate __slots__ for memory efficiency (3.10+, default: False)weakref_slot: Add slot for weak references (3.11+, default: False)Configure individual dataclass fields with custom behavior and metadata.
# Python 3.10+ (with kw_only support)
@overload
def field(
*,
default: _T,
init: bool = ...,
repr: bool = ...,
hash: bool | None = ...,
compare: bool = ...,
metadata: Mapping[Any, Any] | None = ...,
kw_only: bool = ...,
) -> _T: ...
@overload
def field(
*,
default_factory: Callable[[], _T],
init: bool = ...,
repr: bool = ...,
hash: bool | None = ...,
compare: bool = ...,
metadata: Mapping[Any, Any] | None = ...,
kw_only: bool = ...,
) -> _T: ...
@overload
def field(
*,
init: bool = ...,
repr: bool = ...,
hash: bool | None = ...,
compare: bool = ...,
metadata: Mapping[Any, Any] | None = ...,
kw_only: bool = ...,
) -> Any: ...
# Python 3.7-3.9 (without kw_only)
@overload
def field(
*,
default: _T,
init: bool = ...,
repr: bool = ...,
hash: bool | None = ...,
compare: bool = ...,
metadata: Mapping[Any, Any] | None = ...,
) -> _T: ...
@overload
def field(
*,
default_factory: Callable[[], _T],
init: bool = ...,
repr: bool = ...,
hash: bool | None = ...,
compare: bool = ...,
metadata: Mapping[Any, Any] | None = ...,
) -> _T: ...
@overload
def field(
*,
init: bool = ...,
repr: bool = ...,
hash: bool | None = ...,
compare: bool = ...,
metadata: Mapping[Any, Any] | None = ...,
) -> Any: ...Parameters:
default: Default value for the fielddefault_factory: Callable returning default valueinit: Include field in __init__ (default: True)repr: Include field in __repr__ (default: True)hash: Include field in __hash__ calculation (default: None)compare: Include field in comparison methods (default: True)metadata: Additional metadata for the field (default: None)kw_only: Make field keyword-only (3.10+, default: False)Access and examine dataclass field information at runtime.
def fields(class_or_instance: Any) -> tuple[Field[Any], ...]:
"""Return tuple of Field objects for a dataclass."""
def is_dataclass(obj: Any) -> bool:
"""Check if object is a dataclass instance or class."""Convert dataclass instances to standard Python data structures.
@overload
def asdict(obj: Any) -> dict[str, Any]: ...
@overload
def asdict(obj: Any, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ...
@overload
def astuple(obj: Any) -> tuple[Any, ...]: ...
@overload
def astuple(obj: Any, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ...Parameters:
obj: Dataclass instance to convertdict_factory: Custom factory for creating dictionariestuple_factory: Custom factory for creating tuplesCreate modified copies of dataclass instances.
def replace(__obj: _T, **changes: Any) -> _T:
"""Return copy of dataclass instance with specified field changes."""Programmatically create dataclass types at runtime.
# Python 3.11+ (all options)
def make_dataclass(
cls_name: str,
fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]],
*,
bases: tuple[type, ...] = ...,
namespace: dict[str, Any] | None = ...,
init: bool = ...,
repr: bool = ...,
eq: bool = ...,
order: bool = ...,
unsafe_hash: bool = ...,
frozen: bool = ...,
match_args: bool = ...,
kw_only: bool = ...,
slots: bool = ...,
weakref_slot: bool = ...,
) -> type: ...
# Python 3.10+ (without weakref_slot)
def make_dataclass(
cls_name: str,
fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]],
*,
bases: tuple[type, ...] = ...,
namespace: dict[str, Any] | None = ...,
init: bool = ...,
repr: bool = ...,
eq: bool = ...,
order: bool = ...,
unsafe_hash: bool = ...,
frozen: bool = ...,
match_args: bool = ...,
kw_only: bool = ...,
slots: bool = ...,
) -> type: ...
# Python 3.7-3.9 (basic options)
def make_dataclass(
cls_name: str,
fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]],
*,
bases: tuple[type, ...] = ...,
namespace: dict[str, Any] | None = ...,
init: bool = ...,
repr: bool = ...,
eq: bool = ...,
order: bool = ...,
unsafe_hash: bool = ...,
frozen: bool = ...,
) -> type: ...Parameters:
cls_name: Name of the new dataclassfields: Field specifications as strings or tuplesbases: Base classes for inheritancenamespace: Additional namespace for the classRepresents a dataclass field with all its configuration and metadata.
class Field(Generic[_T]):
name: str
type: Type[_T]
default: _T | Literal[_MISSING_TYPE.MISSING]
default_factory: _DefaultFactory[_T] | Literal[_MISSING_TYPE.MISSING]
repr: bool
hash: bool | None
init: bool
compare: bool
metadata: types.MappingProxyType[Any, Any]
# Python 3.10+
kw_only: bool | Literal[_MISSING_TYPE.MISSING]
# Python 3.10+
def __init__(
self,
default: _T,
default_factory: Callable[[], _T],
init: bool,
repr: bool,
hash: bool | None,
compare: bool,
metadata: Mapping[Any, Any],
kw_only: bool,
) -> None: ...
# Python 3.7-3.9
def __init__(
self,
default: _T,
default_factory: Callable[[], _T],
init: bool,
repr: bool,
hash: bool | None,
compare: bool,
metadata: Mapping[Any, Any],
) -> None: ...
def __set_name__(self, owner: Type[Any], name: str) -> None: ...
# Python 3.9+
def __class_getitem__(cls, item: Any) -> GenericAlias: ...Variables used only during initialization, not stored as fields.
class InitVar(Generic[_T]):
type: Type[_T]
def __init__(self, type: Type[_T]) -> None: ...
# Python 3.9+
@overload
def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ...
@overload
def __class_getitem__(cls, type: Any) -> InitVar[Any]: ...class FrozenInstanceError(AttributeError):
"""Raised when attempting to modify a frozen dataclass instance."""# Sentinel value for missing field defaults
MISSING: Literal[_MISSING_TYPE.MISSING]
# Python 3.10+ - Marker for keyword-only fields
class KW_ONLY: ...# Protocol for default factory functions used in Field definitions
class _DefaultFactory(Protocol[_T_co]):
"""Protocol for callables that produce default values for dataclass fields."""
def __call__(self) -> _T_co: ...# Type variables for generic typing
_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True)# Internal enum for MISSING sentinel
class _MISSING_TYPE(enum.Enum):
MISSING = enum.auto()from dataclasses import dataclass, field
from typing import List, Dict, Any
@dataclass
class ComplexData:
# Field with default factory
items: List[str] = field(default_factory=list)
# Field excluded from repr
internal_data: Dict[str, Any] = field(default_factory=dict, repr=False)
# Field excluded from comparison
timestamp: float = field(compare=False)
# Field with metadata
user_id: int = field(metadata={"description": "Unique user identifier"})
# Python 3.10+: Keyword-only field
debug: bool = field(default=False, kw_only=True)from dataclasses import make_dataclass
from typing import List
# Create dataclass dynamically
Point = make_dataclass(
'Point',
[('x', float), ('y', float), ('z', float, 0.0)],
frozen=True
)
# Create instance
point = Point(1.0, 2.0) # z defaults to 0.0from dataclasses import dataclass, FrozenInstanceError
@dataclass(frozen=True)
class ImmutablePoint:
x: float
y: float
point = ImmutablePoint(1.0, 2.0)
try:
point.x = 3.0 # Raises FrozenInstanceError
except FrozenInstanceError:
print("Cannot modify frozen dataclass")from dataclasses import dataclass, fields, is_dataclass
@dataclass
class Person:
name: str
age: int
# Check if object is dataclass
print(is_dataclass(Person)) # True
print(is_dataclass(Person("Alice", 30))) # True
# Get field information
for field in fields(Person):
print(f"Field: {field.name}, Type: {field.type}, Default: {field.default}")