@@ -108,8 +108,8 @@ no annotations.
108
108
It is recommended but not required that checked functions have
109
109
annotations for all arguments and the return type. For a checked
110
110
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
113
113
type of the containing class for instance methods, and a type object
114
114
type corresponding to the containing class object for class methods.
115
115
For example, in class ``A`` the first argument of an instance method
@@ -1152,6 +1152,43 @@ subtype of ``Type[Base]``::
1152
1152
...
1153
1153
1154
1154
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
+
1155
1192
Version and platform checking
1156
1193
-----------------------------
1157
1194
0 commit comments