for with decimal values?

J. Cliff Dyer jcd at sdf.lonestar.org
Tue May 5 13:11:43 EDT 2009


On Sun, 2009-05-03 at 19:48 -0700, alex23 wrote:
> On May 4, 11:41 am, Esmail <ebo... at hotmail.com> wrote:
> > All this discussion makes me wonder if it would be a good idea
> > for Python to have this feature (batteries included and all) - it
> > would have its uses, no?
> 
> Well, sometimes more discussion == less consensus :)
> 
> But it's really easy to roll your own:
> 
> from decimal import Decimal
> 
> def args2dec(fn):
>     '''*args to Decimal decorator'''
>     float2dec = lambda f: Decimal(str(f))
>     def _args2dec(*args):
>         args = map(float2dec, args)
>         return fn(*args)
>     return _args2dec
> 
> @args2dec
> def drange(start, stop, step):
>     while start < stop:
>         yield start
>         start += step

I'd prefer not to force my users into using the Decimal type.  Maybe
float fits their needs better.  So here's a generalized xrange
replacement, which fixes an error in the drange implementation above
(try it with a negative step).  It's also highly *not* optimized.
Calculating i * step every time slows it down.  Speeding it back up is
an exercise for the reader.

def general_xrange(start, stop, step=1):
    target = stop * step
    if start * step > target:
        raise ValueError
    i = start
    while i * step < target:
        yield i
        i += step

Cheers,
Cliff





More information about the Python-list mailing list