Miguel G
Miguel G

Reputation: 175

Which is more Pythonic calling __str__() method or casting to str()?

I have a wrapper class for a dictionary object and I'm curious if one is preferred over the other when implementing the __repr__ method in my class:

class MyClass(object):
  def __init__(self):
    self._obj = dict()
  def __repr__(self):
    return self._obj.__str__()

OR

class MyClass(object):
  def __init__(self):
    self._obj = dict()
  def __repr__(self):
    return str(self._obj)

The second implementation with str() feels right to me. I just want to make sure I'm not missing anything.

Upvotes: 1

Views: 233

Answers (2)

noɥʇʎԀʎzɐɹƆ
noɥʇʎԀʎzɐɹƆ

Reputation: 10657

Ask yourself this: if __str__ was available, why would people use str?

__str__ is just the overload you can use if you want to modify the default str method. Likewise for __len__.

Would you use this?

print(1.__add__(2))

An answer philosophy: Demonstrate core understanding to the asker, preferably having the asker conclude the correct answer by themselves.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 600051

You are right. You should avoid calling the double underscore methods directly: the built-in functions are the Pythonic way of doing this.

(The same is true for example for len(foo) vs foo.__len__().)

Upvotes: 6

Related Questions