Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dataclass inheritance breakes ForwardRef #130506

Closed
Tishka17 opened this issue Feb 24, 2025 · 2 comments
Closed

Dataclass inheritance breakes ForwardRef #130506

Tishka17 opened this issue Feb 24, 2025 · 2 comments
Labels
type-bug An unexpected behavior, bug, or error

Comments

@Tishka17
Copy link

Tishka17 commented Feb 24, 2025

Bug report

Bug description:

If we have two classes split into two files with ForwardRefs, then you cannot get hints on __init__ method of child

parent.py:

from __future__ import annotations  # <--- this triggers the problem

from dataclasses import dataclass


class LocalDep:
    pass


@dataclass
class Parent:
    dep1: LocalDep

child.py

from dataclasses import dataclass
from typing import get_type_hints

from parent import Parent


@dataclass
class Child(Parent):
    pass

print(get_type_hints(Child))
print(get_type_hints(Child.__init__))

I've expected to have two last lines printing the same
Actually, first print gives a correct output, but the second call raises an error

Traceback (most recent call last):
  File "/home/tishka17/src/dishka/tmp/dtc/child.py", line 16, in <module>
    print(get_type_hints(Child.__init__))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/typing.py", line 2414, in get_type_hints
    hints[name] = _eval_type(value, globalns, localns)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/typing.py", line 395, in _eval_type
    return t._evaluate(globalns, localns, recursive_guard)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/typing.py", line 905, in _evaluate
    eval(self.__forward_code__, globalns, localns),
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 1, in <module>
NameError: name 'LocalDep' is not defined

As far as I udnerstood, we inside dataclass logic it copies __init__ method annotations and that leads to an error. We do not copy class attrs (fields), so hints are retrieved from parent class directly (get_type_hints knows about MRO)

CPython versions tested on:

3.11, 3.13, 3.14

Operating systems tested on:

Linux

@Tishka17 Tishka17 added the type-bug An unexpected behavior, bug, or error label Feb 24, 2025
@tuukkamustonen
Copy link

Also #89687

@Tishka17
Copy link
Author

Ok, I'll close it, as it is duplicate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

2 participants