Skip to content

Conformance: Implement Scoping checks for type variables #2454

@fangyi-zhou

Description

@fangyi-zhou

Describe the Bug

See https://typing.python.org/en/latest/spec/generics.html#scoping-rules-for-type-variables for the scoping rules to implement

See test case test_typevar_scoping_restrictions

test_typevar_scoping_restrictions,

from typing import TypeVar, Generic, TypeAlias
from collections.abc import Iterable

T = TypeVar("T")
S = TypeVar("S")

# Unbound TypeVar S used in generic function body
def fun_3(x: T) -> list[T]:
    y: list[T] = []  # OK
    z: list[S] = []  # should error: S not in scope
    return y

# Unbound TypeVar S in class body (not in method)
class Bar(Generic[T]):
    an_attr: list[S] = []  # should error: S not in scope

# Nested class using outer class's TypeVar
class Outer(Generic[T]):
    class Bad(Iterable[T]):  # should error: T from outer not in scope
        ...
    class AlsoBad:
        x: list[T]  # should error: T from outer not in scope

    alias: TypeAlias = list[T]  # should error: T not allowed in TypeAlias here

# Unbound TypeVars at global scope
global_var1: T  # should error
global_var2: list[T] = []  # should error
list[T]()  # should error

Sandbox Link

No response

(Only applicable for extension issues) IDE Information

No response

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions