0

Given this simple class:

class Foo(object):
    def __init__(self,a=None):
        self.a = a
    def __repr__(self):
        return "Foo(a='{self.a}')".format(self=self)

I'm wondering if there is a simple way to get the __repr__ to return different formatting depending on the type of a:

Foo('some_string') # if a is a string
Foo(5)             # if a is the integer 5
Foo(None)          # if a is None

Obviously, for a single attribute I could test and have different output strings but I am thinking that someone must have tackled this before me. Specifically, I have several attributes that can be strings or None and I don't see that writing complicated logic for my __repr__ makes much sense.

tom stratton
  • 668
  • 7
  • 13
  • Thanks to Martijn for the quick answer! Now, does anyone have any "tricks" for dealing with optional parameters? I'm thinking that Foo() is much prettier than Foo(None)... – tom stratton Apr 25 '13 at 22:15

2 Answers2

3

Just use the repr() of self.a:

return "Foo(a={self.a!r})".format(self=self)

The !r tells .format() to call repr() on self.a, instead of calling __format__() on the value, see Format String syntax:

>>> '{!r}'.format(0)
'0'
>>> '{!r}'.format('foo')
"'foo'"

Demo:

>>> Foo(0)
Foo(a=0)
>>> Foo('foo')
Foo(a='foo')
>>> Foo(None)
Foo(a=None)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

While I accepted Martijn's answer, I wanted to explicitly show the results of his suggestion a little more clearly:

>>> class Foo(object):
...     def __init__(self, a=None, b=None):
...         self.a = a
...         self.b = b
...     def __repr__(self):
...         return 'Foo(a={self.a!r}, b={self.b!r})'.format(self=self)
...      
>>> Foo(a='a')
Foo(a='a', b=None)
>>> Foo(a=5)
Foo(a=5, b=None)
tom stratton
  • 668
  • 7
  • 13