[issue15136] Decimal accepting Fraction

Zachary Ware report at bugs.python.org
Thu Aug 23 20:12:00 CEST 2012


Zachary Ware added the comment:

I came across this issue and thought it might be within my means to attempt a patch, so here's the first step towards one.  I liked Terry's suggestion of implementing __format__ using .as_decimal, so that's what I'm working towards with this.

The first part is (or seems to be, I am pretty new at this and may well have missed something obvious :-)) pretty easy.  The attached patch is pretty self-explanatory, I think. I figure if the user wants something specific from their fraction-as-a-decimal, they're probably working with other decimals already and will be able to supply a context.  Otherwise, if they just want to see a decimal representation, they'll probably be fine with the default context and don't have to worry about it.

The __format__ part, though, seems kind of daunting.  For one thing, Decimal's implementation looks pretty hairy and scary from my perspective; duplicating it for Fraction would be quite a feat.  For another, the standard format spec doesn't seem to me to cleanly apply to fractional representations--what should be filled, how should alignment work, how would width be divided up, what exactly does precision mean?

I've had a thought, though; what if Fraction.__format__ simply looks for a 'D' at the end of format_spec?  If it's found, just return format(self.as_decimal(), format_spec[:-1].  Otherwise, format using to-be-determined rules specific to fractions, including rules for, say, mixed fractions or denominator of a certain size.

Thoughts?

----------
keywords: +patch
nosy: +zach.ware
Added file: http://bugs.python.org/file26975/issue15136_as_decimal.patch

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15136>
_______________________________________


More information about the Python-bugs-list mailing list