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
.
To check whether a variable is None or not, use the is operator in Python. With the is operator, use the syntax object is None to return True if the object has the type NoneType and False otherwise.
The Python "AttributeError: 'NoneType' object has no attribute 'append'" occurs when we try to call the append() method on a None value, e.g. assignment from function that doesn't return anything. To solve the error, make sure to only call append() on list objects.
NoneType is the type of the None object which represents a lack of value, for example, a function that does not explicitly return a value will return None .
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
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
andtypes.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With