Where is the NoneType located in Python 3.x?

17,344

Solution 1

types.NoneType is being reintroduced in Python 3.10.

What’s New In Python 3.10

Improved Modules

types

Reintroduced the types.EllipsisType, types.NoneType and types.NotImplementedType classes, providing a new set of types readily interpretable by type checkers. (Contributed by Bas van Beek in bpo-41810.)

The discussion about the change was motivated by a need for types.EllipsisType, leading to types.NoneType also being added for consistency.

Solution 2

You can use type(None) to get the type object, but you want to use isinstance() here, not type() in {...}:

assert isinstance(value, (str, type(None)))

The NoneType object is not otherwise exposed anywhere.

I'd not use type checking for that at all really, I'd use:

assert value is None or isinstance(value, str)

as None is a singleton (very much on purpose) and NoneType explicitly forbids subclassing anyway:

>>> type(None)() is None
True
>>> class NoneSubclass(type(None)):
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'NoneType' is not an acceptable base type
Share:
17,344
Tregoreg
Author by

Tregoreg

Updated on June 02, 2022

Comments

  • Tregoreg
    Tregoreg almost 2 years

    In Python 3, I would like to check whether value is either string or None.

    One way to do this is

    assert type(value) in { str, NoneType }
    

    But where is NoneType located in Python?

    Without any import, using NoneType produces NameError: name 'NoneType' is not defined.