Skip to content

Commit 5baea2e

Browse files
Make NoneType annotation error a new code
Change the code of "NoneType should not be used as a type, please use None instead" error to be a new code, so that people who don't like this rule can disable it easily. I haven't made this a subcode of valid-type because NoneType is actually a valid type; it's just dispreferred. I have added the documentation for the new code, but haven't added any new tests (the old test still runs fine). Fixes #20218
1 parent 66dd2c1 commit 5baea2e

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

docs/source/error_code_list.rst

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,27 @@ You can use :py:class:`~collections.abc.Callable` as the type for callable objec
215215
for x in objs:
216216
f(x)
217217
218+
.. _code-nonetype-type:
219+
220+
Check that NoneType is not used as a type (annotation) [nonetype-type]
221+
----------------------------------------------------------------------
222+
223+
The preferred way to annotate the type of `None` is `None`.
224+
`NoneType` is equivalent, but mypy won't allow it by default.
225+
226+
.. code-block:: python
227+
from types import NoneType
228+
def f(x: None) -> None:
229+
reveal_type(x) # note: Revealed type is "None"
230+
231+
# error: NoneType should not be used as a type, please use None instead [nonetype-type]
232+
def g(x: NoneType) -> None:
233+
reveal_type(x) # note: Revealed type is "None"
234+
235+
# error: NoneType should not be used as a type, please use None instead [nonetype-type]
236+
x1: NoneType = None
237+
x2: None = None #OK
238+
218239
.. _code-metaclass:
219240

220241
Check the validity of a class's metaclass [metaclass]

mypy/errorcodes.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ def __hash__(self) -> int:
6060
"call-overload", "Check that an overload variant matches arguments", "General"
6161
)
6262
VALID_TYPE: Final = ErrorCode("valid-type", "Check that type (annotation) is valid", "General")
63+
NONETYPE_TYPE: Final = ErrorCode("nonetype-type", "Check that type (annotation) is not NoneType", "General")
6364
VAR_ANNOTATED: Final = ErrorCode(
6465
"var-annotated", "Require variable annotation if type can't be inferred", "General"
6566
)

mypy/typeanal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -920,7 +920,7 @@ def analyze_type_with_type_info(
920920
self.fail(
921921
"NoneType should not be used as a type, please use None instead",
922922
ctx,
923-
code=codes.VALID_TYPE,
923+
code=codes.NONETYPE_TYPE,
924924
)
925925
return NoneType(ctx.line, ctx.column)
926926

0 commit comments

Comments
 (0)