Skip to content

Commit baf4af4

Browse files
authored
Treating NoneType as None and warning against using NoneType. (#13153)
### 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.
1 parent 8a974e1 commit baf4af4

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

mypy/typeanal.py

+5
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,11 @@ def analyze_type_with_type_info(
508508
# Create a named TypedDictType
509509
return td.copy_modified(item_types=self.anal_array(list(td.items.values())),
510510
fallback=instance)
511+
512+
if info.fullname == 'types.NoneType':
513+
self.fail("NoneType should not be used as a type, please use None instead", ctx)
514+
return NoneType(ctx.line, ctx.column)
515+
511516
return instance
512517

513518
def analyze_unbound_type_without_type_info(self, t: UnboundType, sym: SymbolTableNode,

test-data/unit/check-python310.test

+9
Original file line numberDiff line numberDiff line change
@@ -1591,3 +1591,12 @@ def test_func(test_str: str) -> str:
15911591
return "special"
15921592
case _:
15931593
return "other"
1594+
1595+
1596+
[case testNoneTypeWarning]
1597+
from types import NoneType
1598+
1599+
def foo(x: NoneType): # E: NoneType should not be used as a type, please use None instead
1600+
reveal_type(x) # N: Revealed type is "None"
1601+
1602+
[builtins fixtures/tuple.pyi]

test-data/unit/lib-stub/types.pyi

+3
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,6 @@ class ModuleType:
1111
if sys.version_info >= (3, 10):
1212
class Union:
1313
def __or__(self, x) -> Union: ...
14+
15+
class NoneType:
16+
...

0 commit comments

Comments
 (0)