Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "test" NoneType in python?

I have a method that sometimes returns a NoneType value. So how can I question a variable that is a NoneType? I need to use if method, for example

if not new:     new = '#' 

I know that is the wrong way and I hope you understand what I meant.

like image 403
CrveniZg Avatar asked Apr 15 '14 14:04

CrveniZg


People also ask

How do you check if something is NoneType in Python?

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.

How do you check if something is not None in Python?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

How do I fix NoneType in Python?

The error “TypeError: 'NoneType' object is not iterable” occurs when you try to iterate over a NoneType object. Objects like list, tuple, and string are iterables, but not None. To solve this error, ensure you assign any values you want to iterate over to an iterable object.


1 Answers

So how can I question a variable that is a NoneType?

Use is operator, like this

if variable is None: 

Why this works?

Since None is the sole singleton object of NoneType in Python, we can use is operator to check if a variable has None in it or not.

Quoting from is docs,

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

Since there can be only one instance of None, is would be the preferred way to check None.


Hear it from the horse's mouth

Quoting Python's Coding Style Guidelines - PEP-008 (jointly defined by Guido himself),

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

like image 111
thefourtheye Avatar answered Sep 30 '22 16:09

thefourtheye