Typing stubs for Python's dataclasses module enabling static type checking
npx @tessl/cli install tessl/pypi-types-dataclasses@0.6.00
# types-dataclasses
1
2
Type 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.
3
4
## Package Information
5
6
- **Package Name**: types-dataclasses
7
- **Package Type**: typing stubs (pypi)
8
- **Language**: Python
9
- **Installation**: `pip install types-dataclasses`
10
- **Python Version Support**: 3.7+
11
12
## Core Imports
13
14
```python
15
from dataclasses import dataclass, field, Field
16
```
17
18
Common imports for working with dataclasses:
19
20
```python
21
from dataclasses import (
22
dataclass, field, Field, fields, asdict, astuple,
23
make_dataclass, replace, is_dataclass, InitVar,
24
FrozenInstanceError, MISSING
25
)
26
```
27
28
Python 3.10+ specific:
29
30
```python
31
from dataclasses import KW_ONLY
32
```
33
34
For type annotations (used internally in stub files):
35
36
```python
37
from builtins import type as Type # Alias to avoid name conflicts
38
from typing import TypeVar
39
from typing_extensions import Literal
40
41
# Type variables used in dataclasses API
42
_T = TypeVar("_T")
43
_T_co = TypeVar("_T_co", covariant=True)
44
```
45
46
## Basic Usage
47
48
```python
49
from dataclasses import dataclass, field
50
from typing import List, Optional
51
52
@dataclass
53
class Person:
54
name: str
55
age: int
56
email: Optional[str] = None
57
hobbies: List[str] = field(default_factory=list)
58
59
# Create instances
60
person = Person("Alice", 30, "alice@example.com")
61
print(person) # Person(name='Alice', age=30, email='alice@example.com', hobbies=[])
62
63
# Use utility functions
64
from dataclasses import asdict, replace
65
66
person_dict = asdict(person)
67
older_person = replace(person, age=31)
68
```
69
70
## Capabilities
71
72
### Dataclass Decorator
73
74
The main decorator for creating dataclasses with configurable behavior options.
75
76
```python { .api }
77
# Python 3.8+ (positional-only cls parameter)
78
@overload
79
def dataclass(__cls: type[_T]) -> type[_T]: ...
80
@overload
81
def dataclass(__cls: None) -> Callable[[type[_T]], type[_T]]: ...
82
83
# Python 3.7 (non-positional-only cls parameter)
84
@overload
85
def dataclass(_cls: type[_T]) -> type[_T]: ...
86
@overload
87
def dataclass(_cls: None) -> Callable[[type[_T]], type[_T]]: ...
88
89
# Python 3.11+ (all options available)
90
@overload
91
def dataclass(
92
*,
93
init: bool = ...,
94
repr: bool = ...,
95
eq: bool = ...,
96
order: bool = ...,
97
unsafe_hash: bool = ...,
98
frozen: bool = ...,
99
match_args: bool = ...,
100
kw_only: bool = ...,
101
slots: bool = ...,
102
weakref_slot: bool = ...,
103
) -> Callable[[type[_T]], type[_T]]: ...
104
105
# Python 3.10+ (without weakref_slot)
106
@overload
107
def dataclass(
108
*,
109
init: bool = ...,
110
repr: bool = ...,
111
eq: bool = ...,
112
order: bool = ...,
113
unsafe_hash: bool = ...,
114
frozen: bool = ...,
115
match_args: bool = ...,
116
kw_only: bool = ...,
117
slots: bool = ...,
118
) -> Callable[[type[_T]], type[_T]]: ...
119
120
# Python 3.7-3.9 (basic options)
121
@overload
122
def dataclass(
123
*,
124
init: bool = ...,
125
repr: bool = ...,
126
eq: bool = ...,
127
order: bool = ...,
128
unsafe_hash: bool = ...,
129
frozen: bool = ...,
130
) -> Callable[[type[_T]], type[_T]]: ...
131
```
132
133
**Parameters:**
134
- `init`: Generate `__init__` method (default: True)
135
- `repr`: Generate `__repr__` method (default: True)
136
- `eq`: Generate `__eq__` method (default: True)
137
- `order`: Generate ordering methods (`__lt__`, `__le__`, `__gt__`, `__ge__`) (default: False)
138
- `unsafe_hash`: Generate `__hash__` method (default: False)
139
- `frozen`: Make instances immutable (default: False)
140
- `match_args`: Generate `__match_args__` for pattern matching (3.10+, default: True)
141
- `kw_only`: Make all fields keyword-only (3.10+, default: False)
142
- `slots`: Generate `__slots__` for memory efficiency (3.10+, default: False)
143
- `weakref_slot`: Add slot for weak references (3.11+, default: False)
144
145
### Field Definition
146
147
Configure individual dataclass fields with custom behavior and metadata.
148
149
```python { .api }
150
# Python 3.10+ (with kw_only support)
151
@overload
152
def field(
153
*,
154
default: _T,
155
init: bool = ...,
156
repr: bool = ...,
157
hash: bool | None = ...,
158
compare: bool = ...,
159
metadata: Mapping[Any, Any] | None = ...,
160
kw_only: bool = ...,
161
) -> _T: ...
162
163
@overload
164
def field(
165
*,
166
default_factory: Callable[[], _T],
167
init: bool = ...,
168
repr: bool = ...,
169
hash: bool | None = ...,
170
compare: bool = ...,
171
metadata: Mapping[Any, Any] | None = ...,
172
kw_only: bool = ...,
173
) -> _T: ...
174
175
@overload
176
def field(
177
*,
178
init: bool = ...,
179
repr: bool = ...,
180
hash: bool | None = ...,
181
compare: bool = ...,
182
metadata: Mapping[Any, Any] | None = ...,
183
kw_only: bool = ...,
184
) -> Any: ...
185
186
# Python 3.7-3.9 (without kw_only)
187
@overload
188
def field(
189
*,
190
default: _T,
191
init: bool = ...,
192
repr: bool = ...,
193
hash: bool | None = ...,
194
compare: bool = ...,
195
metadata: Mapping[Any, Any] | None = ...,
196
) -> _T: ...
197
198
@overload
199
def field(
200
*,
201
default_factory: Callable[[], _T],
202
init: bool = ...,
203
repr: bool = ...,
204
hash: bool | None = ...,
205
compare: bool = ...,
206
metadata: Mapping[Any, Any] | None = ...,
207
) -> _T: ...
208
209
@overload
210
def field(
211
*,
212
init: bool = ...,
213
repr: bool = ...,
214
hash: bool | None = ...,
215
compare: bool = ...,
216
metadata: Mapping[Any, Any] | None = ...,
217
) -> Any: ...
218
```
219
220
**Parameters:**
221
- `default`: Default value for the field
222
- `default_factory`: Callable returning default value
223
- `init`: Include field in `__init__` (default: True)
224
- `repr`: Include field in `__repr__` (default: True)
225
- `hash`: Include field in `__hash__` calculation (default: None)
226
- `compare`: Include field in comparison methods (default: True)
227
- `metadata`: Additional metadata for the field (default: None)
228
- `kw_only`: Make field keyword-only (3.10+, default: False)
229
230
### Field Introspection
231
232
Access and examine dataclass field information at runtime.
233
234
```python { .api }
235
def fields(class_or_instance: Any) -> tuple[Field[Any], ...]:
236
"""Return tuple of Field objects for a dataclass."""
237
238
def is_dataclass(obj: Any) -> bool:
239
"""Check if object is a dataclass instance or class."""
240
```
241
242
### Data Conversion
243
244
Convert dataclass instances to standard Python data structures.
245
246
```python { .api }
247
@overload
248
def asdict(obj: Any) -> dict[str, Any]: ...
249
250
@overload
251
def asdict(obj: Any, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ...
252
253
@overload
254
def astuple(obj: Any) -> tuple[Any, ...]: ...
255
256
@overload
257
def astuple(obj: Any, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ...
258
```
259
260
**Parameters:**
261
- `obj`: Dataclass instance to convert
262
- `dict_factory`: Custom factory for creating dictionaries
263
- `tuple_factory`: Custom factory for creating tuples
264
265
### Instance Modification
266
267
Create modified copies of dataclass instances.
268
269
```python { .api }
270
def replace(__obj: _T, **changes: Any) -> _T:
271
"""Return copy of dataclass instance with specified field changes."""
272
```
273
274
### Dynamic Dataclass Creation
275
276
Programmatically create dataclass types at runtime.
277
278
```python { .api }
279
# Python 3.11+ (all options)
280
def make_dataclass(
281
cls_name: str,
282
fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]],
283
*,
284
bases: tuple[type, ...] = ...,
285
namespace: dict[str, Any] | None = ...,
286
init: bool = ...,
287
repr: bool = ...,
288
eq: bool = ...,
289
order: bool = ...,
290
unsafe_hash: bool = ...,
291
frozen: bool = ...,
292
match_args: bool = ...,
293
kw_only: bool = ...,
294
slots: bool = ...,
295
weakref_slot: bool = ...,
296
) -> type: ...
297
298
# Python 3.10+ (without weakref_slot)
299
def make_dataclass(
300
cls_name: str,
301
fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]],
302
*,
303
bases: tuple[type, ...] = ...,
304
namespace: dict[str, Any] | None = ...,
305
init: bool = ...,
306
repr: bool = ...,
307
eq: bool = ...,
308
order: bool = ...,
309
unsafe_hash: bool = ...,
310
frozen: bool = ...,
311
match_args: bool = ...,
312
kw_only: bool = ...,
313
slots: bool = ...,
314
) -> type: ...
315
316
# Python 3.7-3.9 (basic options)
317
def make_dataclass(
318
cls_name: str,
319
fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]],
320
*,
321
bases: tuple[type, ...] = ...,
322
namespace: dict[str, Any] | None = ...,
323
init: bool = ...,
324
repr: bool = ...,
325
eq: bool = ...,
326
order: bool = ...,
327
unsafe_hash: bool = ...,
328
frozen: bool = ...,
329
) -> type: ...
330
```
331
332
**Parameters:**
333
- `cls_name`: Name of the new dataclass
334
- `fields`: Field specifications as strings or tuples
335
- `bases`: Base classes for inheritance
336
- `namespace`: Additional namespace for the class
337
- All dataclass decorator options available
338
339
## Types
340
341
### Field Class
342
343
Represents a dataclass field with all its configuration and metadata.
344
345
```python { .api }
346
class Field(Generic[_T]):
347
name: str
348
type: Type[_T]
349
default: _T | Literal[_MISSING_TYPE.MISSING]
350
default_factory: _DefaultFactory[_T] | Literal[_MISSING_TYPE.MISSING]
351
repr: bool
352
hash: bool | None
353
init: bool
354
compare: bool
355
metadata: types.MappingProxyType[Any, Any]
356
# Python 3.10+
357
kw_only: bool | Literal[_MISSING_TYPE.MISSING]
358
359
# Python 3.10+
360
def __init__(
361
self,
362
default: _T,
363
default_factory: Callable[[], _T],
364
init: bool,
365
repr: bool,
366
hash: bool | None,
367
compare: bool,
368
metadata: Mapping[Any, Any],
369
kw_only: bool,
370
) -> None: ...
371
372
# Python 3.7-3.9
373
def __init__(
374
self,
375
default: _T,
376
default_factory: Callable[[], _T],
377
init: bool,
378
repr: bool,
379
hash: bool | None,
380
compare: bool,
381
metadata: Mapping[Any, Any],
382
) -> None: ...
383
384
def __set_name__(self, owner: Type[Any], name: str) -> None: ...
385
386
# Python 3.9+
387
def __class_getitem__(cls, item: Any) -> GenericAlias: ...
388
```
389
390
### Init-Only Variables
391
392
Variables used only during initialization, not stored as fields.
393
394
```python { .api }
395
class InitVar(Generic[_T]):
396
type: Type[_T]
397
398
def __init__(self, type: Type[_T]) -> None: ...
399
400
# Python 3.9+
401
@overload
402
def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ...
403
@overload
404
def __class_getitem__(cls, type: Any) -> InitVar[Any]: ...
405
```
406
407
### Exceptions
408
409
```python { .api }
410
class FrozenInstanceError(AttributeError):
411
"""Raised when attempting to modify a frozen dataclass instance."""
412
```
413
414
### Constants and Markers
415
416
```python { .api }
417
# Sentinel value for missing field defaults
418
MISSING: Literal[_MISSING_TYPE.MISSING]
419
420
# Python 3.10+ - Marker for keyword-only fields
421
class KW_ONLY: ...
422
```
423
424
### Protocol Types
425
426
```python { .api }
427
# Protocol for default factory functions used in Field definitions
428
class _DefaultFactory(Protocol[_T_co]):
429
"""Protocol for callables that produce default values for dataclass fields."""
430
def __call__(self) -> _T_co: ...
431
```
432
433
### Type Variables
434
435
```python { .api }
436
# Type variables for generic typing
437
_T = TypeVar("_T")
438
_T_co = TypeVar("_T_co", covariant=True)
439
```
440
441
### Internal Types
442
443
```python { .api }
444
# Internal enum for MISSING sentinel
445
class _MISSING_TYPE(enum.Enum):
446
MISSING = enum.auto()
447
```
448
449
## Usage Examples
450
451
### Advanced Field Configuration
452
453
```python
454
from dataclasses import dataclass, field
455
from typing import List, Dict, Any
456
457
@dataclass
458
class ComplexData:
459
# Field with default factory
460
items: List[str] = field(default_factory=list)
461
462
# Field excluded from repr
463
internal_data: Dict[str, Any] = field(default_factory=dict, repr=False)
464
465
# Field excluded from comparison
466
timestamp: float = field(compare=False)
467
468
# Field with metadata
469
user_id: int = field(metadata={"description": "Unique user identifier"})
470
471
# Python 3.10+: Keyword-only field
472
debug: bool = field(default=False, kw_only=True)
473
```
474
475
### Dynamic Dataclass Creation
476
477
```python
478
from dataclasses import make_dataclass
479
from typing import List
480
481
# Create dataclass dynamically
482
Point = make_dataclass(
483
'Point',
484
[('x', float), ('y', float), ('z', float, 0.0)],
485
frozen=True
486
)
487
488
# Create instance
489
point = Point(1.0, 2.0) # z defaults to 0.0
490
```
491
492
### Frozen Dataclasses
493
494
```python
495
from dataclasses import dataclass, FrozenInstanceError
496
497
@dataclass(frozen=True)
498
class ImmutablePoint:
499
x: float
500
y: float
501
502
point = ImmutablePoint(1.0, 2.0)
503
try:
504
point.x = 3.0 # Raises FrozenInstanceError
505
except FrozenInstanceError:
506
print("Cannot modify frozen dataclass")
507
```
508
509
### Field Introspection
510
511
```python
512
from dataclasses import dataclass, fields, is_dataclass
513
514
@dataclass
515
class Person:
516
name: str
517
age: int
518
519
# Check if object is dataclass
520
print(is_dataclass(Person)) # True
521
print(is_dataclass(Person("Alice", 30))) # True
522
523
# Get field information
524
for field in fields(Person):
525
print(f"Field: {field.name}, Type: {field.type}, Default: {field.default}")
526
```