Python `__format__`: Custom format codes for your own classes

Python `__format__`: Custom format codes for your own classes

Want your Python class to take custom format codes? Define __format__.

This method returns self.x *except* with a :< format. Then it reverses self.x:

def __format__(self, format):
    if format == '<':
        return str(self.x)[::-1]
    else:
        return str(self.x)