661

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
CrveniZg
  • 6,671
  • 2
  • 12
  • 8
  • I think this was answered [here](http://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or) and apparently somewhere before – yorodm Apr 15 '14 at 14:21
  • If `None` is the only value your method returns for which `bool(returnValue)` equals `False`, then `if not new:` ought to work fine. This occurs sometimes in the built-in libs - for example, [`re.match`](https://docs.python.org/2/library/re.html#re.match) returns either None or a truthy match object. – Kevin Apr 15 '14 at 14:21
  • Also see my answer about `null` and `None` in python [here](https://stackoverflow.com/questions/3289601/null-object-in-python/48504780#48504780). – Michael Ekoka May 08 '18 at 09:25

9 Answers9

979

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 6
    So what's the difference between `== None` and `is None`? – NoName Nov 07 '19 at 20:36
  • @NoName With respect to `None`, they both will yield similar result. – thefourtheye Nov 08 '19 at 09:47
  • 8
    this doesn't work if comparing whether a `pandas` DataFrame exists -- for that, I use ``type(df) is type(None)`` to avoid: `The truth value of a DataFrame is ambiguous` – Marc Maxmeister Mar 06 '20 at 18:43
  • @NoName See [Python None comparison: should I use “is” or ==?](https://stackoverflow.com/q/14247373/4518341) – wjandrea Jun 30 '20 at 01:56
  • 10
    `isinstance(instance, type(None))` should be added to make this a complete answer. There are edge cases. For example, if you are building a dynamic tuple of types for validation and the validator is using isinstance (which takes a tuple). – Rafe Dec 10 '20 at 20:26
  • @Rafe None is specific but it's not rare. If you don't expect a value such as None in your validation solution, you really are seeking trouble. A simple lambda will do the job: `isinstance_or_none = lambda x, t: x is None or isinstance(x, t)` – Romain Vincent Jan 18 '21 at 21:56
  • Can we do: `if not variable:`? – alper Jun 02 '21 at 17:11
  • This does not work for me. When I enter: if variable is None I get the error: NameError: name 'variable' is not defined This does work, is there anything better?: '''try: if variable is None: pass except: variable = 10 print (variable)''' – Francis Jul 27 '21 at 09:55
135
if variable is None:
   ...

if variable is not None:
   ...
cs95
  • 379,657
  • 97
  • 704
  • 746
elhoucine
  • 2,356
  • 4
  • 21
  • 37
69

It can also be done with isinstance as per Alex Hall's answer :

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

isinstance is also intuitive but there is the complication that it requires the line

NoneType = type(None)

which isn't needed for types like int and float.

cardamom
  • 6,873
  • 11
  • 48
  • 102
  • 3
    Since you can't subclass `NoneType` and since `None` is a singleton, `isinstance` should not be used to detect `None` - instead you should do as the accepted answer says, and use `is None` or `is not None`. – Russia Must Remove Putin Dec 04 '18 at 18:59
  • 12
    There are edge cases. For example, if you are building a dynamic list of types for validation and the validator is using `isinstance` (which takes a list). – Rafe Dec 10 '20 at 20:24
  • 1
    Correction: tuple, not list – Rafe Dec 10 '20 at 20:32
  • 2
    Also, `assert isinstance(x, str) or x is None` will not result in `x` being inferred as `str | None` by Pyright, but `assert isinstance(x, (str, type(None)))` will. – Timmmm Jun 26 '23 at 15:48
  • Given that current [doc of isinstance](https://web.archive.org/web/20230822114519/https://docs.python.org/3/library/functions.html#isinstance) says nothing about this case I suppose this is valid Python code. However if you use **mypy** be aware of this currently-open [issue](https://github.com/python/mypy/issues/13154). – Gabriel Devillers Aug 24 '23 at 16:16
36

As pointed out by Aaron Hall's comment:

Since you can't subclass NoneType and since None is a singleton, isinstance should not be used to detect None - instead you should do as the accepted answer says, and use is None or is not None.


Original Answer:

The simplest way however, without the extra line in addition to cardamom's answer is probably:
isinstance(x, type(None))

So how can I question a variable that is a NoneType? I need to use if method

Using isinstance() does not require an is within the if-statement:

if isinstance(x, type(None)): 
    #do stuff

Additional information
You can also check for multiple types in one isinstance() statement as mentioned in the documentation. Just write the types as a tuple.

isinstance(x, (type(None), bytes))
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Martin Müsli
  • 1,031
  • 3
  • 14
  • 26
  • 4
    Since you can't subclass `NoneType` and since `None` is a singleton, `isinstance` should not be used to detect `None` - instead you should do as the accepted answer says, and use `is None` or `is not None`. – Russia Must Remove Putin Dec 04 '18 at 19:01
  • 5
    @AaronHall Why `isinstance` **should not** be used ? I understand that `is` should be preferred, but there are some cases where the isinstance form feels more natural (like checking for multiple types at once `isinstance(x, (str, bool, int, type(None)))`). Is it just a personal preference or is there caveat that I'm unaware of ? – Conchylicultor Sep 09 '19 at 13:35
  • 2
    @Conchylicultor downsides to your suggestion: 1. global look-up for `type` 2. then calling it 3. then looking up the type of `None` - when `None` is both a singleton and a keyword. Another downside: 4. this is very non-standard and will raise eyebrows when people are looking at your code. `x is None` is a more optimized check. I would suggest `x is None or isinstance(x, (str, bool, int))` - but I would also suggest you think more about what you're doing when you're doing that kind of type checking for types that don't have a lot in common... – Russia Must Remove Putin Sep 09 '19 at 15:17
17

Not sure if this answers the question. But I know this took me a while to figure out. I was looping through a website and all of sudden the name of the authors weren't there anymore. So needed a check statement.

if type(author) == type(None):
     print("my if body")
else:
     print(" my else body")

Author can be any variable in this case, and None can be any type that you are checking for.

Roland
  • 4,619
  • 7
  • 49
  • 81
Joshua Pachner
  • 179
  • 1
  • 2
2

Python 2.7 :

x = None
isinstance(x, type(None))

or

isinstance(None, type(None))

==> True

Pesko
  • 61
  • 1
  • 8
0

I hope this example will be helpful for you)

print(type(None))  # NoneType

So, you can check type of the variable name

# Example
name = 12  # name = None

if type(name) is type(None):
    print("Can't find name")
else:
    print(name)
sausix
  • 251
  • 2
  • 6
alexmosk25
  • 134
  • 1
  • 2
  • 12
  • Because `None` is a singleton and `None` is the only instance of `NoneType`, your example is more complicated than necessary. Just check your variable for `None`: `if name is None: ...` – sausix Dec 03 '20 at 12:18
0

I mostly use the following method to check for NoneType.

if (new): # not None
  ...
else: # NoneType
  ...
Chandragupta Borkotoky
  • 1,596
  • 1
  • 11
  • 16
0

You can test explicitly for NoneType by importing it:

>>> from types import NoneType

or, without import:

>>> NoneType = type(None)

When is this useful?

When you have a variable that's optional which can be either set to its type or to None. Now you want to validate its type using a single isinstance call:

>>> from types import NoneType
>>> foo = 'bar'
>>> assert isinstance(foo, (str, NoneType))

which is equivalent to:

>>> assert isinstance(foo, str) or isinstance(foo, NoneType)

as well as:

>>> assert isinstance(foo, str) or (foo is None)
Lars Blumberg
  • 19,326
  • 11
  • 90
  • 127