Multiple output formats for __str__

Viewed 133

I want to write a __str__ for my class. However, the class has many members and not all may always be relevant. I want the __str__ to include only the key members by default, but include more if the user asks for more.

How can I do this? Can __str__ take parameters (I am okay with giving them default values)? How will these parameters be passed when the user does print(my_class_instance)?

1 Answers

The most common way of doing this in python is to define a __format__ method so that you can use format specifiers much like "{:05.3f}" can format floating point numbers.

If you only need 2 representations, one to be more user friendly and one to be more descriptive you may be able to get away with just defining __str__ and __repr__, for context __repr__ is used when displaying values in an interactive terminal or when calling repr or using "{0!r}".format.

Here is a sample code to get you started:

class Demo:
    def __init__(self, a,b):
        self.a = a
        self.b = b
    def __repr__(self):
        # should usually have a repr method to show code representation
        return "Demo({0.a!r}, {0.b!r})".format(self)
    def __str__(self):
        # str should give user friendly representation, default format
        return "Demo()"
    def __format__(self, spec):
        # format for more specific details
        if spec == "": # usually empty spec should be equivalent to str.
            return str(self)
        elif spec == "d":
            return "(a:{0.a}, b:{0.b})".format(self)
        else:
            raise NotImplementedError("unsupported spec: {!r}".format(spec))

x = Demo("A", "B")
print("str: {0}, repr: {0!r}, spec='d': {0:d}".format(x))

print("WILL THROW ERROR: {0:OTHER_SPEC}".format(x))

You can make any format spec you wish, what ever is passed into the specifier will be passed to the __format__ method as a string.

Related