1

The commom way to test variable for NoneType is checking if it is referring to None singletone:

test_var is None

This approach is recommended as the only way to check for None according to PEP-8:

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

Although sometimes I find the following test in different sources:

isinstance(test, type(None))

This way looks OK, but I can't quite figure out why simple and readable construction may be replaced with isinstance. Is it more useful for some cases or maybe referred to codestyle?

UPD: the only NoneType checking with isinstance I find really useful (so far):

isinstance(None, (NoneType, str, float))
Oleh Rybalchenko
  • 6,998
  • 3
  • 22
  • 36
  • 1
    Sounds like some programmer saw `NoneType` in an error message and decided to test for that without really understanding the problem. There's no benefit. – user2357112 Nov 22 '17 at 18:02
  • 1
    https://media1.tenor.com/images/fb50f8dd802894fce6bdafef59ddd84d/tenor.gif – Martijn Pieters Nov 22 '17 at 18:02
  • You can also do `type(test) == None.__class__` and it'd work. The point being, a developer is free to achieve the solution in any way possible, it doesn't always mean that there is a reason behind it. – Matias Cicero Nov 22 '17 at 18:03
  • ok, but this way is mentioned even in some SO posts, so I really interested to clarify about its useless. Can't understand why the question is voted down, btw. – Oleh Rybalchenko Nov 22 '17 at 18:09
  • @MartijnPieters This is the right one hahaha: https://giphy.com/gifs/the-office-no-michael-scott-ToMjGpx9F5ktZw8qPUQ – Elis Byberi Nov 22 '17 at 18:18
  • @OlegRybalchenko: I can't find any other Stack Overflow post that uses that method. – Martijn Pieters Nov 22 '17 at 21:13
  • @MartijnPieters: for example this one: https://stackoverflow.com/questions/40553285/determining-a-variables-type-is-nonetype-in-python However, the accepted answer mentioned `is` as prefered way – Oleh Rybalchenko Nov 22 '17 at 21:37
  • 1
    @OlegRybalchenko It is becoming too mainstream: https://stackoverflow.com/a/17198511/2430448 – Elis Byberi Nov 22 '17 at 23:12

1 Answers1

4

No, there is never a reason to use that construct.

You can't subclass NoneType. The only object that would ever pass that test is the None singleton. That line was probably written by someone that didn't know this and thought they needed to test for subclasses too.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343