Skip to content
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

A way to spell "SelfType", the type of self #271

Closed
gvanrossum opened this issue Aug 28, 2016 · 3 comments
Closed

A way to spell "SelfType", the type of self #271

gvanrossum opened this issue Aug 28, 2016 · 3 comments

Comments

@gvanrossum
Copy link
Member

See python/mypy#1212. The proposal does not require changes to typing.py but it could benefit from words in PEP 484 requiring that this works.

The idea is simple: in an instance method, you can add a type annotation for self which is a type variable, and make the return type use that same type variable, e.g.

T = TypeVar('T', bound='Copyable')
class Copyable:
    def copy(self: T) -> T:
        # return a copy of self
class C(Copyable): ...
c = C()
c2 = c.copy()  # type here should be C

It should also work for class methods, using Type[], e.g.

T = TypeVar('T', bound='C')
class C:
    def factory(cls: Type[T]) -> T:
        # make a new instance of cls
class D(C): ...
d = D.factory()  # type here should be D

Note that the Python 2 annotation syntax already supports this, e.g.

T = TypeVar('T', bound='Copyable')
class Copyable:
    def copy(self):
        # type: (T) -> T
        # etc.

(IOW if you have a method with self and three arguments, you can give it either 3 or 4 arguments in the # type: comment, and if 4, the first will be used for self. Ditto for class methods.)

@ilevkivskyi
Copy link
Member

I think this is a good idea. As I understand, not much should be changed in PEP 484. The main part would be to implement this in mypy. I could not help with mypy now, but I would like to make a PR with changes in the PEP text.

@gvanrossum
Copy link
Member Author

gvanrossum commented Aug 31, 2016 via email

@ilevkivskyi
Copy link
Member

OK, here is the PR python/peps#89

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