Skip to content

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

@gvanrossum

Description

@gvanrossum

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.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions