Borislav Hadzhiev
Wed Apr 20 2022·3 min read
Photo by Stephen Leonardi
The Python "TypeError: unsupported operand type(s) for +: 'NoneType' and
'str'" occurs when we try to use the addition (+) operator with a None
value.
To solve the error, figure out where the variable got assigned a None
value
and correct the assignment.
Here is an example of how the error occurs.
my_str_1 = None my_str_2 = 'world' # ⛔️ TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' result = my_str_1 + my_str_2
The variable on the left-hand side of the addition operator stores a None
value which caused the error.
None
value and correct the assignment.The most common sources of None
values are:
None
implicitly).None
.Make sure you aren't calling a function that doesn't return anything and expecting the return value to be a string.
# 👇️ this function returns None def get_str(): print('hello ') my_str_2 = 'world' # ⛔️ TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' result = get_str() + my_str_2
The get_str
function doesn't return anything, therefore it implicitly returns
None
.
You can use a return
statement to return a value from a function.
def get_str(): return 'hello ' my_str_2 = 'world' result = get_str() + my_str_2 print(result) # 👉️ "hello world"
Use an if
statement if you need to check whether a variable doesn't store a
None
value before using the addition (+) operator.
my_str_1 = None my_str_2 = 'world' if my_str_1 is not None: result = my_str_1 + my_str_2 print(result) else: # 👇️ this runs print('variable stores a None value')
Alternatively, you can provide a default value if the variable stores None
.
my_str_1 = None my_str_2 = 'world' if my_str_1 is None: my_str_1 = '' result = my_str_1 + my_str_2 print(result) # 👉️ 'world'
We check if the my_str_1
variable stores a None
value and if it does, we set
it to an empty string.
sort()
) that mutate the original object in place and return None
.Make sure you aren't storing the result of calling one in a variable.
Another common cause of the error is having a function that returns a value only if a condition is met.
def get_str(a): if len(a) > 5: return a my_str_1 = get_str('hello') print(my_str_1) # 👉️ None my_str_2 = 'world' # ⛔️ TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' result = my_str_1 + my_str_2
The if
block in the get_str
function is only ran if the passed in string has
a length greater than 5
.
None
.To solve the error in this scenario, 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_str(a): if len(a) > 5: return a return '' # 👈️ return empty string if condition not met my_str_1 = get_str('hello') print(my_str_1) # 👉️ "" my_str_2 = 'world' result = my_str_1 + my_str_2 print(result) # 👉️ 'world'
Now the function is guaranteed to return a value regardless if the condition is met.