-
Book Overview & Buying
-
Table Of Contents
Python Essentials
By :
We can easily offer alternative implementations of a given feature. If we want more speed, more accuracy, or less memory use, we should be able to import an alternative definition of a given library.
We can compare the math and cmath modules for a concrete example of this principle. Here's an example of how they differ:
>>> import math >>> import cmath >>> math.sqrt(-1) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: math domain error >>> cmath.sqrt(-1) 1j
The math module includes a square root function, which we used as math.sqrt(). This produces only real-valued results, and must raise an exception when confronted with an expression that's not real-valued.
The cmath module also includes a square root function. The cmath.sqrt() function can return complex values instead of raising an exception. Since the packages are so similar, we can substitute one...