python-attrs / python-attrs/attrs

`typing.get_type_hints` cannot resolve forward references in `cls.__init__` annotations

Open
#1,021 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Typing
Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Description

The is related to #593/#760. Because #760 populates the generated __init__ method's globals at the time that the class is created, new globals aren't visible to get_type_hints by default.

Example code demonstrating this:

import attrs
import typing

@attrs.define
class HasForwardRef:
    ref: "ClassDefinedLater"

class ClassDefinedLater:
    pass

typing.get_type_hints(HasForwardRef.__init__)

This last call raises an error.

I've got a workaround for this in the code where I hit this, but it really wasn't obvious at first what was going on.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the issue's example and trace how attrs generates HasForwardRef.init and populates its globals when the class is created. Investigate how typing.get_type_hints resolves that method's forward references; done means the shown call succeeds after ClassDefinedLater is defined, with regression coverage for the example.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.