@@ -2429,6 +2429,75 @@ Functions and decorators
2429
2429
2430
2430
.. versionadded :: 3.11
2431
2431
2432
+ .. decorator :: dataclass_transform
2433
+
2434
+ :data: `~typing.dataclass_transform ` may be used to
2435
+ decorate a class, metaclass, or a function that is itself a decorator.
2436
+ The presence of ``@dataclass_transform() `` tells a static type checker that the
2437
+ decorated object performs runtime "magic" that
2438
+ transforms a class, giving it :func: `dataclasses.dataclass `-like behaviors.
2439
+
2440
+ Example usage with a decorator function::
2441
+
2442
+ T = TypeVar("T")
2443
+
2444
+ @dataclass_transform()
2445
+ def create_model(cls: type[T]) -> type[T]:
2446
+ ...
2447
+ return cls
2448
+
2449
+ @create_model
2450
+ class CustomerModel:
2451
+ id: int
2452
+ name: str
2453
+
2454
+ On a base class::
2455
+
2456
+ @dataclass_transform()
2457
+ class ModelBase: ...
2458
+
2459
+ class CustomerModel(ModelBase):
2460
+ id: int
2461
+ name: str
2462
+
2463
+ On a metaclass::
2464
+
2465
+ @dataclass_transform()
2466
+ class ModelMeta(type): ...
2467
+
2468
+ class ModelBase(metaclass=ModelMeta): ...
2469
+
2470
+ class CustomerModel(ModelBase):
2471
+ id: int
2472
+ name: str
2473
+
2474
+ The ``CustomerModel `` classes defined above will
2475
+ be treated by type checkers similarly to classes created with
2476
+ :func: `@dataclasses.dataclass <dataclasses.dataclass> `.
2477
+ For example, type checkers will assume these classes have
2478
+ ``__init__ `` methods that accept ``id `` and ``name ``.
2479
+
2480
+ The arguments to this decorator can be used to customize this behavior:
2481
+
2482
+ * ``eq_default `` indicates whether the ``eq `` parameter is assumed to be
2483
+ ``True `` or ``False `` if it is omitted by the caller.
2484
+ * ``order_default `` indicates whether the ``order `` parameter is
2485
+ assumed to be True or False if it is omitted by the caller.
2486
+ * ``kw_only_default `` indicates whether the ``kw_only `` parameter is
2487
+ assumed to be True or False if it is omitted by the caller.
2488
+ * ``field_specifiers `` specifies a static list of supported classes
2489
+ or functions that describe fields, similar to ``dataclasses.field() ``.
2490
+ * Arbitrary other keyword arguments are accepted in order to allow for
2491
+ possible future extensions.
2492
+
2493
+ At runtime, this decorator records its arguments in the
2494
+ ``__dataclass_transform__ `` attribute on the decorated object.
2495
+ It has no other runtime effect.
2496
+
2497
+ See :pep: `681 ` for more details.
2498
+
2499
+ .. versionadded :: 3.11
2500
+
2432
2501
.. decorator :: overload
2433
2502
2434
2503
The ``@overload `` decorator allows describing functions and methods
0 commit comments