Skip to content

Nested generic self type error #5482

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
alanhdu opened this issue Aug 15, 2018 · 1 comment
Closed

Nested generic self type error #5482

alanhdu opened this issue Aug 15, 2018 · 1 comment

Comments

@alanhdu
Copy link
Contributor

alanhdu commented Aug 15, 2018

mypy does not seem to like generic self types. Running mypy 0.620 with Python 3.6.6 on the following code

from typing import Generic, List, TypeVar

T = TypeVar("T")


class Nested(Generic[T]):
    def __init__(self, x: T) -> None:
        self.x = [x]

    def get(self: "Nested[List[T]]") -> T:
        return self.x[0][0]


n = Nested([1])
reveal_type(n)
reveal_type(n.x)
y = n.get()
reveal_type(y)

gives us

scratch.py:15: error: Revealed type is 'scratch.Nested[builtins.list*[builtins.int*]]'
scratch.py:16: error: Revealed type is 'builtins.list[builtins.list*[builtins.int*]]'
scratch.py:18: error: Revealed type is 'builtins.list*[builtins.int*]'

This is pretty weird -- y should be an int, not List[int], and mypy seems to do the type inference in the get method just fine.

@ilevkivskyi
Copy link
Member

This doesn't work like this. You can't have arbitrary annotation on self (at least currently). There are similar requests, #5320, #5305. I am closing this as a duplicate of those.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants