python / python/typing

`get_type_hints` occurs NameError only if import `__future__.annotations`

Open
#2,132 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: other
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

from typing import get_type_hints


class A[T]:
    def __init__(self, x: T):
        self.x = x

    def foo(self):
        def bar() -> T:
            return self.x

        print(get_type_hints(bar))


A[int](5).foo()

Output: {'return': T}

from __future__ import annotations  # Add this

from typing import get_type_hints


class A[T]:
    def __init__(self, x: T):
        self.x = x

    def foo(self):
        def bar() -> T:
            return self.x

        print(get_type_hints(bar))


A[int](5).foo()

Error:

NameError: name 'T' is not defined

Is this the expected behavior?

Also, is there a way to make it work if __future__.annotations is imported?

Contributor guide

No contributing guide indexed for this repository

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

Reproduce both examples and compare how typing.get_type_hints resolves the local function's return annotation with and without future.annotations. Then inspect the get_type_hints implementation and its tests for generic aliases and deferred annotations; done means the expected behavior and any supported workaround are established in the issue or covered by a targeted regression test.

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
Needs clarification
Newbie friendliness
28/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.