TypeError: __str__ returned non-string (type NoneType)

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: __str__ returned non-string (type NoneType) #

The Python "TypeError: __str__ returned non-string (type NoneType)" occurs when we forget to return a value from the __str__() method. To solve the error, make sure to return a string from the method.

typeerror str returned non string type nonetype

Here is an example of how the error occurs.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): print(self.name) # 👈️ forgot to return value emp = Employee('Alice', 100) # ⛔️ TypeError: __str__ returned non-string (type NoneType) print(emp)

We forgot to return a value from the __str__() method in the Employee class.

To solve the error, use a return statement to return a string from the method.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return self.name # 👈️ return a string emp = Employee('Alice', 100) print(emp) # 👉️ Alice

The return value of the __str__() method must be a string object.

If the value you are returning is not a string, use the str() class to convert it.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return str(self.salary) # 👈️ return a string emp = Employee('Alice', 100) print(emp) # 👉️ 100

We used the str class to convert the integer to a string.

You can use a formatted string literal if you need to include expressions in a string.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return f'Name of employee: {self.name}' emp = Employee('Alice', 100) print(emp) # 👉️ Name of employee: Alice
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

The __str__() method is called by str(object) and the built-in functions format() and print() and returns the informal string representation of the object.

Conclusion #

The Python "TypeError: __str__ returned non-string (type NoneType)" occurs when we forget to return a value from the __str__() method. To solve the error, make sure to return a string from the method.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.