Should None be considered a data type? (Python)

Viewed 44

I know this sounds stupid, but I'm reading a programming book and they talk about how print() can return nothing (None). They use this code to explain it.

a = 10
b = 15

c = print('a =', a, 'b=', b)

print(c)

I get it, c isn't any data type that print() can take and, y'know, print it. c just has an empty value because it's not a valid data type.

But what data type is c? What data type is None? If c isn't a string, integer, float, nor a boolean, what is it? Shouldn't None be it's own data type?

P.S. If I go to python and assign a variable None and print it, it recognises the data value and does not spit a name error. So theoretically, *None is it's own data type, right?

Oh, and why does Python not convert c to string and then print it?

1 Answers

None is (like literally everything else in Python besides keywords) an object. Meaning it is an instance of a class (or type if you will). None is an instance of NoneType, which you can find out, if you do this:

print(type(None))

So yes, None has its own data type in Python.

The class is special in the sense that it only ever has one instance: None. And yes, there is a string representation defined for the NoneType class. And the string representation is, well "None", which you see, when you do this: (all equivalent in this case)

print(None)
print(str(None))
print(repr(None))

PS:

It is also worth stressing that None is in fact a singleton. Meaning there only ever is exactly that one instance of the NoneType class. This is why you can do identity comparisons with None, i.e.:

if my_variable is None:
    ...

As opposed to equality comparisons (which of course work too) like this:

if my_variable == None:
    ...

And when any function (including built-ins like print) have no explicit return statement or an empty one (like return without anything after it), they implicitly always return that one special None object.

Related