Skip to content

Commit

Permalink
[mypyc] always add implicit None return type to __init__ method (#9866)
Browse files Browse the repository at this point in the history
Fixes mypyc/mypyc#792.

Always give __init__ an implicit None return type so that programs like

```
class C:
    def __init__(self):  # missing `-> None` annotation
        pass
```

compile.
  • Loading branch information
thomasjohns authored Jan 8, 2021
1 parent 0996c42 commit 0c5936e
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
7 changes: 6 additions & 1 deletion mypyc/irbuild/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,12 @@ def fdef_to_sig(self, fdef: FuncDef) -> FuncSignature:
else:
# Handle unannotated functions
arg_types = [object_rprimitive for arg in fdef.arguments]
ret = object_rprimitive
# We at least know the return type for __init__ methods will be None.
is_init_method = fdef.name == '__init__' and bool(fdef.info)
if is_init_method:
ret = none_rprimitive
else:
ret = object_rprimitive

args = [RuntimeArg(arg_name, arg_type, arg_kind)
for arg_name, arg_kind, arg_type in zip(fdef.arg_names, fdef.arg_kinds, arg_types)]
Expand Down
10 changes: 10 additions & 0 deletions mypyc/test-data/run-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,16 @@ o = object()
c1.d = o
assert c1.d is o

[case testInitMethodWithMissingNoneReturnAnnotation]
class C:
def __init__(self):
self.x = 42
[file driver.py]
from native import C
c = C()
assert c is not None
assert c.x == 42

[case testConstructClassWithDefaultConstructor]
class C:
a: int
Expand Down
9 changes: 9 additions & 0 deletions mypyc/test-data/run-functions.test
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,15 @@ def f(x):
from native import f
assert f(3) == 6

[case testUnannotatedModuleLevelInitFunction]
# Ensure that adding an implicit `-> None` annotation only applies to `__init__`
# _methods_ specifically (not module-level `__init__` functions).
def __init__():
return 42
[file driver.py]
from native import __init__
assert __init__() == 42

[case testComplicatedArgs]
from typing import Tuple, Dict

Expand Down

0 comments on commit 0c5936e

Please sign in to comment.