Collect the fields of a dataclass. Args: cls: dataclass. config_wrapper: The config wrapper instance. ns_resolver: Namespace resolver to use when getting dataclass annotations. Defaults to an empty instance. typevars_map: A dictionary mapping type var
(
cls: type[StandardDataclass],
*,
config_wrapper: ConfigWrapper,
ns_resolver: NsResolver | None = None,
typevars_map: dict[Any, Any] | None = None,
)
| 525 | |
| 526 | |
| 527 | def collect_dataclass_fields( |
| 528 | cls: type[StandardDataclass], |
| 529 | *, |
| 530 | config_wrapper: ConfigWrapper, |
| 531 | ns_resolver: NsResolver | None = None, |
| 532 | typevars_map: dict[Any, Any] | None = None, |
| 533 | ) -> dict[str, FieldInfo]: |
| 534 | """Collect the fields of a dataclass. |
| 535 | |
| 536 | Args: |
| 537 | cls: dataclass. |
| 538 | config_wrapper: The config wrapper instance. |
| 539 | ns_resolver: Namespace resolver to use when getting dataclass annotations. |
| 540 | Defaults to an empty instance. |
| 541 | typevars_map: A dictionary mapping type variables to their concrete types. |
| 542 | |
| 543 | Returns: |
| 544 | The dataclass fields. |
| 545 | """ |
| 546 | FieldInfo_ = import_cached_field_info() |
| 547 | |
| 548 | fields: dict[str, FieldInfo] = {} |
| 549 | ns_resolver = ns_resolver or NsResolver() |
| 550 | dataclass_fields = cls.__dataclass_fields__ |
| 551 | |
| 552 | # The logic here is similar to `_typing_extra.get_cls_type_hints`, |
| 553 | # although we do it manually as stdlib dataclasses already have annotations |
| 554 | # collected in each class: |
| 555 | for base in reversed(cls.__mro__): |
| 556 | if not dataclasses.is_dataclass(base): |
| 557 | continue |
| 558 | |
| 559 | with ns_resolver.push(base): |
| 560 | for ann_name, dataclass_field in dataclass_fields.items(): |
| 561 | base_anns = _typing_extra.safe_get_annotations(base) |
| 562 | |
| 563 | if ann_name not in base_anns: |
| 564 | # `__dataclass_fields__`contains every field, even the ones from base classes. |
| 565 | # Only collect the ones defined on `base`. |
| 566 | continue |
| 567 | |
| 568 | globalns, localns = ns_resolver.types_namespace |
| 569 | ann_type, evaluated = _typing_extra.try_eval_type(dataclass_field.type, globalns, localns) |
| 570 | |
| 571 | if _typing_extra.is_classvar_annotation(ann_type): |
| 572 | continue |
| 573 | |
| 574 | if ( |
| 575 | not dataclass_field.init |
| 576 | and dataclass_field.default is dataclasses.MISSING |
| 577 | and dataclass_field.default_factory is dataclasses.MISSING |
| 578 | ): |
| 579 | # TODO: We should probably do something with this so that validate_assignment behaves properly |
| 580 | # Issue: https://github.com/pydantic/pydantic/issues/5470 |
| 581 | continue |
| 582 | |
| 583 | if isinstance(dataclass_field.default, FieldInfo_): |
| 584 | if dataclass_field.default.init_var: |
no test coverage detected