You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/developer/type_annotation_guide.md
+28Lines changed: 28 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -242,6 +242,34 @@ over
242
242
approach over the `Generator` one because it's more understandable and easier
243
243
to read.
244
244
245
+
**`__init__` should always have a return annotation**
246
+
247
+
You might think that adding the `-> None` return annotation to `_init_` functions is unnecessary. However, from [PEP-484](https://peps.python.org/pep-0484/):
248
+
> Note that the return type of `__init__` ought to be annotated with `-> None`. The reason for this is subtle.
249
+
> If `__init__` assumed a return annotation of `-> None`, would that mean that an argument-less, un-annotated `__init__` method should still be type-checked?
250
+
> Rather than leaving this ambiguous or introducing an exception to the exception, we simply say that `__init__` ought to have a return annotation; the default behavior is thus the same as for other methods.
251
+
252
+
Mypy explains this with this code example:
253
+
254
+
```python
255
+
classUntypedExample:
256
+
# This method is not type-checked at all!
257
+
def__init__(self):
258
+
self.voltage =0.0
259
+
260
+
classTypedExample:
261
+
# This is how to ensure that a 0-argument __init__ is type-checked:
262
+
def__init__(self) -> None:
263
+
self.voltage =0.0
264
+
```
265
+
266
+
(from the [mypy 0.641 release notes](https://mypy-lang.blogspot.com/2018/10/mypy-0640-released.html))
0 commit comments