Skip to content

Commit

Permalink
Treating NoneType as None and warning against using NoneType. (#13153)
Browse files Browse the repository at this point in the history
### Description

Fixes #11288

Warns people to not use `NoneType` as a type annotation, as requested in #11288.

### Example

**Before**

```python
from types import NoneType

def f(x: NoneType) -> None:
    pass

f(None) # E: Argument 1 to "f" has incompatible type "None"; expected "NoneType"
```

**After**

```python
from types import NoneType

def f(x: NoneType) -> None: # E: NoneType should not be used as a type, please use None instead 
    pass

f(None)
```

Had to edit `test-data/unit/lib-stub/types.pyi` to allow NoneType type annotation.
  • Loading branch information
strny0 committed Jul 17, 2022
1 parent 8a974e1 commit baf4af4
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
5 changes: 5 additions & 0 deletions mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,11 @@ def analyze_type_with_type_info(
# Create a named TypedDictType
return td.copy_modified(item_types=self.anal_array(list(td.items.values())),
fallback=instance)

if info.fullname == 'types.NoneType':
self.fail("NoneType should not be used as a type, please use None instead", ctx)
return NoneType(ctx.line, ctx.column)

return instance

def analyze_unbound_type_without_type_info(self, t: UnboundType, sym: SymbolTableNode,
Expand Down
9 changes: 9 additions & 0 deletions test-data/unit/check-python310.test
Original file line number Diff line number Diff line change
Expand Up @@ -1591,3 +1591,12 @@ def test_func(test_str: str) -> str:
return "special"
case _:
return "other"


[case testNoneTypeWarning]
from types import NoneType

def foo(x: NoneType): # E: NoneType should not be used as a type, please use None instead
reveal_type(x) # N: Revealed type is "None"

[builtins fixtures/tuple.pyi]
3 changes: 3 additions & 0 deletions test-data/unit/lib-stub/types.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ class ModuleType:
if sys.version_info >= (3, 10):
class Union:
def __or__(self, x) -> Union: ...

class NoneType:
...

0 comments on commit baf4af4

Please sign in to comment.