Please can someone explain why I get the following error when using %r with tuples?
>>> repr((1,2))
'(1, 2)'
>>> class Foo(object):
... def __init__(self,vals):
... self.vals=vals
... def __repr__(self):
... return "Foo(%r)" % self.vals
...
>>> foo = Foo((1,2))
>>> foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __repr__
TypeError: not all arguments converted during string formatting
What is the appropriate way for printing out __repr__? Should I be using %s and repr(self.vals) instead?
The
%operator takes a tuple itself, so you are basically doing this:Wrap
self.valsin a one-element tuple:In principle you can use a string defined in a variable too:
in which case you want to leave it up to that variable (perhaps taken from a configuration file?) how to format
self.vals, be it%ror%s.You could also use the
.format()method instead:This format gives you more flexibility with the input given; you could address individual items in the
valstuple, for example:which would result in
Foo((0001, 04))for your example input.