Skip to content

Commit 4ee7c73

Browse files
committed
Typing: add note on return annotation for init functions
1 parent 001b59f commit 4ee7c73

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

docs/developer/type_annotation_guide.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,34 @@ over
242242
approach over the `Generator` one because it's more understandable and easier
243243
to read.
244244

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+
class UntypedExample:
256+
# This method is not type-checked at all!
257+
def __init__(self):
258+
self.voltage = 0.0
259+
260+
class TypedExample:
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))
267+
268+
Some more info:
269+
- https://typing.python.org/en/latest/spec/annotations.html
270+
271+
272+
245273
### Common Types
246274

247275
To ensure a consistent use of type annotations in Rucio, here is a list of

0 commit comments

Comments
 (0)