PEP 484: Allow annotating first argument of instance and class methods (#89)

This commit is contained in:
Ivan Levkivskyi 2016-11-01 16:15:17 +01:00 committed by Guido van Rossum
parent a1cd7fb7c8
commit ada7d3566e
1 changed files with 39 additions and 2 deletions

View File

@ -108,8 +108,8 @@ no annotations.
It is recommended but not required that checked functions have
annotations for all arguments and the return type. For a checked
function, the default annotation for arguments and for the return type
is ``Any``. An exception is that the first argument of instance and
class methods does not need to be annotated; it is assumed to have the
is ``Any``. An exception is the first argument of instance and
class methods. If it is not annotated, then it is assumed to have the
type of the containing class for instance methods, and a type object
type corresponding to the containing class object for class methods.
For example, in class ``A`` the first argument of an instance method
@ -1152,6 +1152,43 @@ subtype of ``Type[Base]``::
...
Annotating instance and class methods
-------------------------------------
In most cases the first argument of class and instance methods
does not need to be annotated, and it is assumed to have the
type of the containing class for instance methods, and a type object
type corresponding to the containing class object for class methods.
In addition, the first argument in an instance method can be annotated
with a type variable. In this case the return type may use the same
type variable, thus making that method a generic function. For example::
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
The same applies to class methods using ``Type[]`` in an annotation
of the first argument::
T = TypeVar('T', bound='C')
class C:
@classmethod
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 some type checkers may apply restrictions on this use, such as
requiring an appropriate upper bound for the type variable used
(see examples).
Version and platform checking
-----------------------------