Just for a background, context notion could be also used to control exceptions, coming from “invalid” FPE in a different way, producing a complex results:
>>> import gmpy2
>>> gmpy2.sqrt(-1) # gmpy2 has different defaults: to show Annex F special values
mpfr('nan')
>>> gmpy2.get_context().trap_invalid=True
>>> gmpy2.sqrt(-1) # here is how math.sqrt(-1) behave (exception is a subclass of ValueError)
Traceback (most recent call last):
File "<python-input-4>", line 1, in <module>
gmpy2.sqrt(-1)
~~~~~~~~~~^^^^
gmpy2.InvalidOperationError: invalid operation
>>> gmpy2.get_context().allow_complex = True
>>> gmpy2.sqrt(-1) # but we also could show a complex result!
mpc('0.0+1.0j')
See recent discussion on PEP 791, starting from this.
Similar context notion could be also useful for integer arithmetic. See this and this.