[Python-Dev] Re: Future division detection

Michael Hudson mwh@python.net
05 Nov 2001 11:48:16 -0500


com-nospam@ccraig.org (Christopher A. Craig) writes:

> "Tim Peters" <tim.one@home.com> writes:
> 
> > [Christopher A. Craig, playing with modifying the meaning of division]
> > > ...
> > > While doing this I was thinking that I would change true_division on
> > > ints and floats to return a rational and change the rational code to
> > > return a long if the denominator is 1.  This works great, except that
> > > if future division is off then rationals can suddenly become longs and
> > > do not automatically cast back.  This makes it virtually impossible to
> > > guarantee a correct result to nearly any rational computation that
> > > involves a division.
> > >
> > > So I wanted to know if there is some way to detect, at the object
> > > level, if the CO_FUTURE_DIVISION feature is active.
> > 
> > I'm unclear on what you're asking.  In case it helps, note this section in
> > __future__.py:
> > 
> 
> Hmm, I thought I was being too verbose, I guess I was being too
> unclear.  I have a rational module (in C) which I am trying to patch
> to be an object satisfying PEP-239.  The problem is that I would like
> to have an rational cast back to a integer iff (1) the denominator is 1
> and (2) future division is active.
> 
> If I don't check (2) then I get the situation that if future division
> is inactive then `(rational('1/3')*3)/5` would yield 0 instead of 1/5.
> This makes rationals pretty much useless unless future division is
> active.
> 
> What I would like to do is have a function that can check to see if
> the CO_FUTURE_DIVISION flag is set and if it is and the denominator is
> 1 then return the numerator, else return the rational.
> 
> I have a strong suspicion that this can't be done, in which case I
> just won't do the cast back automatically.

Does this:

int is_future_div(void)
{
        PyCompilerFlags cf;
        PyEval_MergeCompilerFlags(&cf);
        return cf.cf_flags & CO_FUTURE_DIVISION;
}

work?

You'll need to change this when future division becomes the default,
but I think it'll work today.  This is a murky dark corner of the
interpreter, though -- so don't blame me when it breaks!

Cheers,
M.

-- 
                    >> REVIEW OF THE YEAR, 2000 <<
                   It was shit. Give us another one.
                          -- NTK Know, 2000-12-29, http://www.ntk.net/