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…

2
  • 1
    I'm pretty sure this can't be done. Is there any reason why you're avoiding using format? Commented May 7, 2013 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()). Commented May 9, 2013 at 3:37

2 Answers 2

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('<'))
Sign up to request clarification or add additional context in comments.

Comments

-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'

2 Comments

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).
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.