Skip to content

Commit ada7d35

Browse files
ilevkivskyigvanrossum
authored andcommitted
PEP 484: Allow annotating first argument of instance and class methods (#89)
1 parent a1cd7fb commit ada7d35

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

pep-0484.txt

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ no annotations.
108108
It is recommended but not required that checked functions have
109109
annotations for all arguments and the return type. For a checked
110110
function, the default annotation for arguments and for the return type
111-
is ``Any``. An exception is that the first argument of instance and
112-
class methods does not need to be annotated; it is assumed to have the
111+
is ``Any``. An exception is the first argument of instance and
112+
class methods. If it is not annotated, then it is assumed to have the
113113
type of the containing class for instance methods, and a type object
114114
type corresponding to the containing class object for class methods.
115115
For example, in class ``A`` the first argument of an instance method
@@ -1152,6 +1152,43 @@ subtype of ``Type[Base]``::
11521152
...
11531153

11541154

1155+
Annotating instance and class methods
1156+
-------------------------------------
1157+
1158+
In most cases the first argument of class and instance methods
1159+
does not need to be annotated, and it is assumed to have the
1160+
type of the containing class for instance methods, and a type object
1161+
type corresponding to the containing class object for class methods.
1162+
In addition, the first argument in an instance method can be annotated
1163+
with a type variable. In this case the return type may use the same
1164+
type variable, thus making that method a generic function. For example::
1165+
1166+
T = TypeVar('T', bound='Copyable')
1167+
class Copyable:
1168+
def copy(self: T) -> T:
1169+
# return a copy of self
1170+
1171+
class C(Copyable): ...
1172+
c = C()
1173+
c2 = c.copy() # type here should be C
1174+
1175+
The same applies to class methods using ``Type[]`` in an annotation
1176+
of the first argument::
1177+
1178+
T = TypeVar('T', bound='C')
1179+
class C:
1180+
@classmethod
1181+
def factory(cls: Type[T]) -> T:
1182+
# make a new instance of cls
1183+
1184+
class D(C): ...
1185+
d = D.factory() # type here should be D
1186+
1187+
Note that some type checkers may apply restrictions on this use, such as
1188+
requiring an appropriate upper bound for the type variable used
1189+
(see examples).
1190+
1191+
11551192
Version and platform checking
11561193
-----------------------------
11571194

0 commit comments

Comments
 (0)