◐ Shell
clean mode source ↗

gh-137855: Lazy import `inspect` module in dataclasses by danielhollas · Pull Request #144387 · python/cpython

As a side effect that may be worth noting, deferring __doc__ generation also 'fixes' the output for self referential dataclasses1.

@dataclass
class Example:
    examples: list[Example]

print(Example.__doc__)

Before:

"Example(examples: list[ForwardRef('Example', is_class=True, owner=<class '__main__.Example'>)])"

PR:

'Example(examples: list[__main__.Example])'

Every dataclass is getting its own _AutoDocString instance, could they share the same instance?

Following on from this, the re and copy imports could also potentially be deferred, copy is only used in some cases for the serialization methods and re is only used for string annotations.

Deferring re only makes sense if inspect is also deferred as inspect currently eagerly imports it (I see you have a PR to change that too though).

Footnotes

  1. Arguably dataclasses should probably be doing something with Format.STRING here, other forward references are still ugly but that would be a separate issue.