(f, frozen, globals, self_name, slots)
| 589 | |
| 590 | |
| 591 | def _field_init(f, frozen, globals, self_name, slots): |
| 592 | # Return the text of the line in the body of __init__ that will |
| 593 | # initialize this field. |
| 594 | |
| 595 | default_name = f'__dataclass_dflt_{f.name}__' |
| 596 | if f.default_factory is not MISSING: |
| 597 | if f.init: |
| 598 | # This field has a default factory. If a parameter is |
| 599 | # given, use it. If not, call the factory. |
| 600 | globals[default_name] = f.default_factory |
| 601 | value = (f'{default_name}() ' |
| 602 | f'if {f.name} is __dataclass_HAS_DEFAULT_FACTORY__ ' |
| 603 | f'else {f.name}') |
| 604 | else: |
| 605 | # This is a field that's not in the __init__ params, but |
| 606 | # has a default factory function. It needs to be |
| 607 | # initialized here by calling the factory function, |
| 608 | # because there's no other way to initialize it. |
| 609 | |
| 610 | # For a field initialized with a default=defaultvalue, the |
| 611 | # class dict just has the default value |
| 612 | # (cls.fieldname=defaultvalue). But that won't work for a |
| 613 | # default factory, the factory must be called in __init__ |
| 614 | # and we must assign that to self.fieldname. We can't |
| 615 | # fall back to the class dict's value, both because it's |
| 616 | # not set, and because it might be different per-class |
| 617 | # (which, after all, is why we have a factory function!). |
| 618 | |
| 619 | globals[default_name] = f.default_factory |
| 620 | value = f'{default_name}()' |
| 621 | else: |
| 622 | # No default factory. |
| 623 | if f.init: |
| 624 | if f.default is MISSING: |
| 625 | # There's no default, just do an assignment. |
| 626 | value = f.name |
| 627 | elif f.default is not MISSING: |
| 628 | globals[default_name] = f.default |
| 629 | value = f.name |
| 630 | else: |
| 631 | # If the class has slots, then initialize this field. |
| 632 | if slots and f.default is not MISSING: |
| 633 | globals[default_name] = f.default |
| 634 | value = default_name |
| 635 | else: |
| 636 | # This field does not need initialization: reading from it will |
| 637 | # just use the class attribute that contains the default. |
| 638 | # Signify that to the caller by returning None. |
| 639 | return None |
| 640 | |
| 641 | # Only test this now, so that we can create variables for the |
| 642 | # default. However, return None to signify that we're not going |
| 643 | # to actually do the assignment statement for InitVars. |
| 644 | if f._field_type is _FIELD_INITVAR: |
| 645 | return None |
| 646 | |
| 647 | # Now, actually generate the field assignment. |
| 648 | return _field_assign(frozen, f.name, value, self_name) |
no test coverage detected
searching dependent graphs…