Skip to content

Type variables of a nested generic function are confused with type variables of surrounding generic function #1335

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

Closed
rwbarton opened this issue Apr 6, 2016 · 2 comments
Labels
bug mypy got something wrong

Comments

@rwbarton
Copy link
Contributor

rwbarton commented Apr 6, 2016

from typing import TypeVar
T = TypeVar('T')
U = TypeVar('U')

def outer(x: T) -> T:
    def inner(y: U) -> T: ...
    return inner(1)    # error: Incompatible return value type: expected T`-1, got builtins.int*

I should be able to pass inner a value of any type and get back a T to return from outer. But internally the type variables U and T of inner have the same id (-1) so effectively mypy thinks inner has a type like (U) -> U.

@gvanrossum
Copy link
Member

Ah. This probably explains why we ran into problems trying to define the type of certain decorators correctly.

@gvanrossum gvanrossum added this to the 0.3.2 milestone Apr 6, 2016
rwbarton added a commit to rwbarton/mypy that referenced this issue Apr 6, 2016
We need to avoid reusing an id that is already assigned to a type
variable of an enclosing generic function. Fixes python#1335.
@JukkaL
Copy link
Collaborator

JukkaL commented Apr 6, 2016

Yeah, type variables were originally implemented with various restrictions such as no nested (generic) functions that weren't enforced or were lifted later without fixing the underlying issues. The current way of doing type inference of generics also causes the two-namespace-approach to not work correctly in other contexts. (Though I'm not quite sure if generics ever worked without any scoping issues, and the namespace hack was questionable from the beginning.)

@JukkaL JukkaL added the bug mypy got something wrong label Apr 6, 2016
@JukkaL JukkaL closed this as completed in 1de3562 Apr 6, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants