[Python-Dev] RE: Future division detection

Tim Peters tim.one@home.com
Sat, 3 Nov 2001 23:21:10 -0500


[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:

# The CO_xxx symbols are defined here under the same names used by
# compile.h, so that an editor search will find them here.  However,
# they're not exported in __all__, because they don't really belong to
# this module.
CO_NESTED            = 0x0010   # nested_scopes
CO_GENERATOR_ALLOWED = 0x1000   # generators
CO_FUTURE_DIVISION   = 0x2000   # division

A code object's co_flags member is a mask made up of these (among other)
bits:

>>> def f():
...    a/b
...
>>> hex(f.func_code.co_flags)
'0x3'
>>> from __future__ import division
>>> def f():
...     a/b
...
>>> hex(f.func_code.co_flags)
'0x2003'
>>>

So if you can get at a code object, you can tell whether it was compiled
with future division by checking its co_flags 0x2000 bit.  This is internal
implementation detail, though, and there's NO GUARANTEE we won't reuse the
0x2000 bit for some other purpose in some future release.