Designing alternative implementations

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 ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.