[New-bugs-announce] [issue45524] Cross-module dataclass inheritance breaks get_type_hints

Aidan Clark report at bugs.python.org
Tue Oct 19 10:37:47 EDT 2021


New submission from Aidan Clark <aidan.b.clark at gmail.com>:

[I believe this is fundamentally a dataclass version of https://bugs.python.org/issue41249]

When using `from __future__ import annotations`, calling get_type_hints on the constructor of a dataclass B which inherits from a dataclass A defined in another module will error if dataclass A has type hints which are not imported in the module where dataclass B is defined.

This is best shown by example, if you have foo.py:

```
from __future__ import annotations

import collections
import dataclasses

@dataclasses.dataclass
class A:
  x: collections.OrderedDict
```

and then in bar.py:

```
from __future__ import annotations

import foo
import dataclasses
import typing

@dataclasses.dataclass
class B(foo.A):
  pass

typing.get_type_hints(B)
```

the final line will raise "NameError: name 'collections' is not defined".


This code will not error if you do either of the following:
  * add `import collections` to bar.py.
  * remove the __future__ annotations import from both files.


I am not confident enough on the internals of dataclass to suggest a fix, but potentially a similar approach to that which solved the TypedDict equivalent https://bugs.python.org/issue41249 would work?

----------
components: Library (Lib)
messages: 404307
nosy: aidan.b.clark, slebedev
priority: normal
severity: normal
status: open
title: Cross-module dataclass inheritance breaks get_type_hints
type: behavior
versions: Python 3.6, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45524>
_______________________________________


More information about the New-bugs-announce mailing list