The Python error “TypeError: str returned non-string (type NoneType)” means you aren’t returning a string from your class’ __str__
method. To fix this, make sure you’re actually returning a string.
Python has methods called “dunder” methods, which is shorthand for “double underscore”. They are special methods you can add to your classes to do things like, in this case, automatically convert your instantiated class to a string when treated as such (for example, when placed in an f-string like this: f"My Class: {my_class}"
.
These “dunder” methods only work if you hold up your end of the bargain; i.e., return the type they’re supposed to be converting to.
Table of Contents
Problem: you’re not returning a str from __str__
Let’s say you have the following class defined, and are trying to make use of the __str__
dunder method:
class MyClass:
def __init__(self, some_string):
self.my_string = some_string
def __str__(self):
print(self.my_string)
my_class = MyClass("Hello world!")
print(str(my_class))
PythonIf you’re new to Python, this might seem correct to you. After all, you want to print the value of my_string
when you treat the class instance as a string. However, if you try to run this, you’ll get the following error:
Hello world!
Traceback (most recent call last):
File "/home/user/main.py", line 9, in <module>
print(str(my_class))
TypeError: __str__ returned non-string (type NoneType)
As you can see, it first printed out “Hello world!” like we were expecting, then it threw an error complaining that you didn’t return a str
from the method. Well, it’s not lying, we didn’t! We called print
which doesn’t return anything, not to mention we never put a return
statement in our method to begin with. And when a method doesn’t “return” anything, it really returns the value None
, hence the error message.
Solution: make sure you’re returning a string
This is an easy enough problem to fix. Just return self.my_string
instead of printing it:
class MyClass:
def __init__(self, some_string):
self.my_string = some_string
def __str__(self):
return self.my_string
my_class = MyClass("Hello world!")
print(str(my_class))
# -> Hello world!
PythonConclusion
Python’s special “dunder” method __str__
must return a string, or you’ll get this error. Take a look at your stack trace, see where it’s originating, and make sure that the __str__
method it’s complaining about is actually returning a str
.
John is a professional software engineer who has been solving problems with code for 15+ years. He has experience with full stack web development, container orchestration, mobile development, DevOps, Windows and Linux kernel development, cybersecurity, and reverse engineering. In his spare time, he’s researching the potential business applications of AI.