[Python-3000] str.format() -- poss. code or doc bug?
Mark Summerfield
mark at qtrac.eu
Fri Nov 30 17:08:16 CET 2007
On 2007-11-30, Eric Smith wrote:
> Mark Summerfield wrote:
> > Hi,
> >
> > I'm using Python 30a.
> >
> > The docs for str.format()'s 'g' format say
> > "General format. This prints the number as a fixed-point number,
> > unless the number is too large, in which case it switches to 'e'
> > exponent notation."
> > The fixed-point format uses the 'f' character.
> >
> > But this does not seem to happen in practice:
> >>>> "[{0:12.4e}] [{0:12.4f}] [{0:12.4g}]".format(10**4 * math.pi)
> >
> > '[ 3.1416e+04] [ 31415.9265] [ 3.142e+04]'
> >
> >>>> "[{0:12.4e}] [{0:12.4f}] [{0:12.4g}]".format(10**3 * math.pi)
> >
> > '[ 3.1416e+03] [ 3141.5927] [ 3142]'
> >
> > I thought this was a bug in Python 3, but Python 2 does the same thing:
> >>>> n = 10**4 * math.pi
> >>>> m = 10**3 * math.pi
> >>>> "[%12.4e] [%12.4f] [%12.4g]" % (n, n, n)
> >
> > '[ 3.1416e+04] [ 31415.9265] [ 3.142e+04]'
> >
> >>>> "[%12.4e] [%12.4f] [%12.4g]" % (m, m, m)
> >
> > '[ 3.1416e+03] [ 3141.5927] [ 3142]'
>
> They're the same because I copied the '%' code when I created the
> __format__ code. I copied, instead of refactoring and using the same
> code, because at the time I did it I thought the direction was going to
> be to remove '%' formatting. Plus, the string/unicode work was making
> it more complex at the time. If I had it to do over, I might spend some
> more time refactoring, or maybe even modifying '%' to call str.format()
> internally.
>
> As to whether the documentation or the code is correct, I can't say
> which is correct or more desirable. Changing how this works would no
> doubt break all sorts of code.
I have no opinion, I just wanted to know which was right.
Your reply seems to imply that Python 3 will have 3 different and
overlapping ways of formatting strings: %, str.format(), and
string.Template. If that is the case, it seems like overkill to me:-)
> > Python 2's docs are different from Python 3's regarding 'g' format:
> > "Floating point format. Uses exponential format if exponent is
> > greater than -4 or less than precision, decimal format otherwise."
> > There is no "decimal format", but there is "Signed integer decimal"
> > format which is what seems to being used.
> >
> > So is this a doc bug?
> >
> > BTW I notice that decimal.Decimal() numbers can't be used with the 'e',
> > 'f', or 'g' formats. I know that these numbers aren't floating-point
> > under the hood, but this still seems a bit counter-intuitive to me.
--
Mark Summerfield, Qtrac Ltd., www.qtrac.eu
More information about the Python-3000
mailing list