Situation: I'm new to python and currently trying to learn the ropes, I've attempted creating a linked list class to assist in getting a better understanding of the language and its structures. I know that the __repr__ function is basically supposed to return the same thing as __str__ but I'm unsure on what the actual difference is.
Here's my class so far:
class LinkedList: class Node: def __init__(self, val, prior=None, next=None): self.val = val self.prior = prior self.next = next def __init__(self): self.head = LinkedList.Node(None) self.head.prior = self.head.next = self.head self.length = 0 def __str__(self): """Implements `str(self)`. Returns '[]' if the list is empty, else returns `str(x)` for all values `x` in this list, separated by commas and enclosed by square brackets. E.g., for a list containing values 1, 2 and 3, returns '[1, 2, 3]'.""" if len(self)==0: return '[]' else: return '[' + ', '.join(str(x) for x in self) + ']' def __repr__(self): """Supports REPL inspection. (Same behavior as `str`.)""" return '[' + ', '.join(str(x) for x in self) + ']' When I test this code against the below code, I'll get an error basically saying the blank string '[]' isn't actually being returned when using the repr function. How could I edit this methods body to fix this issue? I've also tried return str(self) and I'm not sure why that won't work either.
from unittest import TestCase tc = TestCase() lst = LinkedList() tc.assertEqual('[]', str(lst)) tc.assertEqual('[]', repr(lst)) lst.append(1) tc.assertEqual('[1]', str(lst)) tc.assertEqual('[1]', repr(lst))
__repr__function is basically supposed to return the same thing as__str__" - I'm not sure how you know that, but that's not right, see the docs on__str__and__repr__.__len__and__iter__methods, at least), which makes troubleshooting it very difficult. While we appreciate a concise question, we need a minimal reproducible example that actually works!