Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Joshua Rawson-Harris
The Python "TypeError: '<' not supported between instances of 'NoneType' and
'int'" occurs when we use a comparison operator between a None
value and a
int
. To solve the error, figure out where the None
value comes from and
correct the assignment.
Here is an example of how the error occurs.
my_int_1 = None my_int_2 = 10 # ⛔️ TypeError: '<' not supported between instances of 'NoneType' and 'int' if my_int_1 < my_int_2: print('success')
We used a comparison operator between values of incompatible types (None
and
int
) which caused the error.
None
value comes from and correct the assignment or conditionally check if the variable doesn't store None
.The most common sources of None
values are:
None
implicitly).None
.Functions that don't explicitly return a value return None
.
# 👇️ this function returns None def get_int(): print(20) my_int_2 = 10 # ⛔️ TypeError: '>' not supported between instances of 'NoneType' and 'int' if get_int() > my_int_2: print('success')
You can use a return
statement to return a value from a function.
def get_int(): return 20 my_int_2 = 10 if get_int() > my_int_2: # ✅ this runs print('success')
Use an if
statement if you need to check whether a variable doesn't store a
None
value before using a comparison operator.
my_int_1 = None my_int_2 = 10 if my_int_1 is not None: print(my_int_1 < my_int_2) else: # 👉️ this runs print('Variable stores a None value')
Alternatively, you can set the variable to 0
if it stores None
.
my_int_1 = None my_int_2 = 10 if my_int_1 is None: my_int_1 = 0 print(my_int_1 < my_int_2) # 👉️ True
If the my_int_1
variable stores a None
value, we set it to 0
before using
a comparison operator.
Another common cause of the error is having a function that returns a value only if a condition is met.
def get_int(a): if a > 5: return a my_int_1 = get_int(4) print(my_int_1) # 👉️ None my_int_2 = 10 # ⛔️ TypeError: '>' not supported between instances of 'NoneType' and 'int' print(my_int_1 > my_int_2)
The if
statement in the get_int
function is only ran if the passed in number
is greater than 5
.
None
.To solve the error, you either have to check if the function didn't return
None
, or return a default value if the condition is not met.
def get_int(a): if a > 5: return a return 0 my_int_1 = get_int(4) print(my_int_1) # 👉️ 0 my_int_2 = 10 print(my_int_1 > my_int_2) # 👉️ False
Now the function is guaranteed to return a value regardless if the condition is met.