Eric O. Lebigot
Eric O. Lebigot

Reputation: 94475

Can custom formatting through the % operator be done in Python?

Is it possible to have a class be formatted in its own specific way with the % operator, in Python? I am interested in a case where the format string would be something like %3z (not simply %s or %r, which are handled by the __str__() and __repr__() methods). Said differently: Python 2.6+ allows classes to define a __format__() method: is there an equivalent for the % operator?

I tried to define the __rmod()__ method, hoping that str.__mod__() would return NotImplemented and that __rmod()__ would be called, but "%3z" % … returns ValueError: unsupported format character 'z' instead…

Upvotes: 0

Views: 120

Answers (2)

lvc
lvc

Reputation: 35059

There isn't. This customizability is one of the major benefits of the format method over % formatting. If it wasn't novel, PEP 3101 wouldn't need to discuss this aspect of it in so much detail.

If you need to support older versions of Python than have new-style string formatting, the best you can do is to implement a custom conversion function on your class, and expect clients to call it like this:

'%4f %s' % (5, myobj.str('<'))

Upvotes: 2

mdscruggs
mdscruggs

Reputation: 1212

You might find this helpful: operator overloading in python

__mod__ and __rmod__ are included here: http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types

Don't bother trying to reinvent Python's string formatting mini-language...use it to your advantage: http://docs.python.org/2/library/string.html#format-specification-mini-language

EDIT: you probably got at least this far, but since we're here to code:

class moddableObject(object):
    def __mod__(self, arg)
        return 'got format arg: {}'.format(arg)

moddable = moddableObject()
print moddable % 'some string'

Upvotes: -1

Related Questions