TypeError: __str__ returned non-string (type tuple)

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Yayan Sopian

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

The Python "TypeError: __str__ returned non-string (type tuple)" occurs when we return a tuple value from the __str__() method. To solve the error, use a formatted string literal to include expressions in a string and return a string instead.

typeerror str returned non string type tuple

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): return self.name, self.salary # 👈️ this is a tuple emp = Employee('Carl', 50) # ⛔️ TypeError: __str__ returned non-string (type tuple) print(emp)

We returned an integer from the __str__() method, but the method must return 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'{self.name} {self.salary}' emp = Employee('Carl', 50) print(emp) # 👉️ Carl 50
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.

In case you declared a tuple by mistake, tuples are constructed in multiple ways:

  • Using a pair of parenthesis () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor

If you meant to return an element of a tuple, access it at its specific index, e.g. my_tuple[0].

If the element is not a string, use the str() class to convert it to a string, e.g. str(my_tuple[0]).

Use the search field on my Home Page to filter through my more than 1,000 articles.