0

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…

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
  • 1
    I'm pretty sure this can't be done. Is there any reason why you're avoiding using format? – mgilson May 07 '13 at 12:57
  • There is a reason: the formatting will be applied to the numbers with uncertainty of my uncertainties package, which works with all version of Python *starting with 2.3* (versions 2.3 to 2.5 only have `%` and not `format()`). – Eric O. Lebigot May 09 '13 at 03:37

2 Answers2

2

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('<'))
lvc
  • 34,233
  • 10
  • 73
  • 98
-1

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'
Community
  • 1
  • 1
mdscruggs
  • 1,182
  • 7
  • 15
  • 1
    OP clearly already knows how operator overloading works - he has specifically tried implementing `moddableObject.__rmod__` to find that `'some string' % moddable` doesn't call it (since `str.__mod__` raises an exception rather than returning `NotImplemented`). – lvc May 07 '13 at 13:55
  • hence my comment, "you probably got at least this far, but since we're here to code"...I put it there so others could see a quick example (and so I could try it out myself). – mdscruggs May 07 '13 at 13:59