Turn off ZeroDivisionError?

Christian Heimes lists at cheimes.de
Sun Feb 10 21:49:07 EST 2008


Mark Dickinson wrote:
> Any suggestions about how to achieve the above-described state of
> affairs are welcome!

I have worked out a suggestion in three parts.

Part 1
------

The PyFloat C API gets two more functions:

int PyFloat_SetIEEE754(int new_state) -> old state
int PyFloat_GetIEEE754(void) -> current state

By default the state is 0 which means no IEEE 754 return values for
1./0.,  0./0. and maybe some other places. An op like 1./0. raises an
exception.

With state 1 float ops like f/0. returns copysign(INF, f) and for f=0.
it returns a NaN.

ints and longs aren't affected by the state.

The state is to be stored and fetched from Python's thread state object.
This could slow down floats a bit because every time f/0. occurs the
state has to be looked up in the thread state object.

Part 2
------

The two function are exposed to Python code as math.set_ieee754 and
math.get_ieee754. As an alternative the functions could be added to a
new module ieee754 or to the float type.

Part 3
------

contextlib gets a new context for ieee754

class ieee754(object):
    def __init__(self, state=1):
        self.new_state = state

    def __enter__(self):
        self.old_state = math.set_ieee754(self.new_state)

    def __exit__(self, *args):
        math.set_ieee754(self.old_state)

usage:

with contextlib.ieee754():
    ...

Christian





More information about the Python-list mailing list