A more flexible formatting proposal

Antoon Pardon apardon at forel.vub.ac.be
Thu May 6 07:16:15 EDT 2004


It is my impression that the python developpers haven't
taken advantage of the Object Oriented nature of python
when it comes to formatting: So I have the following
proposal.

Allow classes to have a special method __format__,
that will be called when the object has to be represented
in a specific format. A little example of how it could
be used follows. Maybe instead of __format__ we could
use the __str__ method for this. But then somekind
of additional checking should be done to see if the
__str__ method allows for an addition form argument
or not.


class fstring (str):

  def __mod__(self , args):
    strng = ' ' + self + 'a'
    result = ''
    si = 0
    ai = 0
    i = strng.find('%' , si)
    while i >= 0:
      if strng[i + 1] == '%':
        si = i + 2
        result = result + '%'
      else:
        result = result + strng[si:i]
        for ti in range(i + 1 , len(strng)):
          if strng[ti].isalpha():
            break
        if ti < len(strng) - 1:
          frm = strng[i : ti + 1]
          si = ti + 1
          if hasattr(args[ai] , '__format__'):
            result = result + args[ai].__format__(frm)
          else:
            result = result + frm % (args[ai],)
          ai = ai + 1
        else:
          si = ti
      i = strng.find('%' , si)
    result = result + strng[si:]
    return result[1:-1]
    return str.__mod__(self , args)


class Int (int):

  def __format__(self, frm):
    nr = abs(self)
    if frm[-1] == 'b':
      res=''
      while nr > 0:
        res = `nr % 2` + res
        nr = nr / 2
      return res
    else:
      return frm % (self,)

Nr = Int(26)
print '%f + %f = %f' % (3.2 , 1.4 , 4.6)
print fstring('%f + %f = %f') % (3.2 , 1.4 , 4.6)
print fstring('%b %o  %x  %d') % (Nr, Nr, Nr, Nr)




More information about the Python-list mailing list