A more flexible formatting proposal

A

Antoon Pardon

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top