Skip to content

Commit 41b40aa

Browse files
le0tanilevkivskyi
authored andcommitted
Update common issues to include __init__ without arguments (#8303)
This is the implication of #5677 where the return type of `__init__` is inferred given that at least one argument is typed. However, if no argument is present in `__init__`, `-> None` becomes compulsory if we are to enable type-checking on that method without using `--check-untyped-defs` flag. I believe it is worth mentioning in the section of "No errors reported for obviously wrong code".
1 parent da5bad2 commit 41b40aa

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/source/common_issues.rst

+26
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,32 @@ flagged as an error.
7272
e.g. the :py:func:`pow` builtin returns ``Any`` (see `typeshed issue 285
7373
<https://github.com/python/typeshed/issues/285>`_ for the reason).
7474

75+
- **:py:meth:`__init__ <object.__init__>` method has no annotated
76+
arguments or return type annotation.** :py:meth:`__init__ <object.__init__>`
77+
is considered fully-annotated **if at least one argument is annotated**,
78+
while mypy will infer the return type as ``None``.
79+
The implication is that, for a :py:meth:`__init__ <object.__init__>` method
80+
that has no argument, you'll have to explicitly annotate the return type
81+
as ``None`` to type-check this :py:meth:`__init__ <object.__init__>` method:
82+
83+
.. code-block:: python
84+
85+
def foo(s: str) -> str:
86+
return s
87+
88+
class A():
89+
def __init__(self, value: str): # Return type inferred as None, considered as typed method
90+
self.value = value
91+
foo(1) # error: Argument 1 to "foo" has incompatible type "int"; expected "str"
92+
93+
class B():
94+
def __init__(self): # No argument is annotated, considered as untyped method
95+
foo(1) # No error!
96+
97+
class C():
98+
def __init__(self) -> None: # Must specify return type to type-check
99+
foo(1) # error: Argument 1 to "foo" has incompatible type "int"; expected "str"
100+
75101
- **Some imports may be silently ignored**. Another source of
76102
unexpected ``Any`` values are the :option:`--ignore-missing-imports
77103
<mypy --ignore-missing-imports>` and :option:`--follow-imports=skip

0 commit comments

Comments
 (0)