Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the NoneType located in Python 3.x?

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.

like image 262
Tregoreg Avatar asked Feb 11 '14 15:02

Tregoreg


People also ask

Where can I find NoneType?

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.

Why is Python saying my list is NoneType?

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.

What does NoneType mean?

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 .


2 Answers

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 
like image 189
Martijn Pieters Avatar answered Oct 09 '22 09:10

Martijn Pieters


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.

like image 26
bad_coder Avatar answered Oct 09 '22 09:10

bad_coder