Deciding which types to use

Because of the conversions, we see the following four general domains of numerical processing:

  • Complex: Once we get involved in complex math, we'll be using complex, and float, plus the cmath module. We probably aren't going to use Fraction or Decimal at all. However, there's no reason to impose restrictions on the numeric types; most numbers can be converted to complex.
  • Currency: For currency-related operations, we absolutely must use Decimal. Generally, when doing currency calculations, there's no good reason to mix the decimal values with non-decimal values. Sometimes, we'll use the int values, but there's no good reason to work with float or complex along with Decimal. Remember, floats are approximations, and that's unacceptable when working with currency.
  • Bit Kicking: For operations that involve bit and byte processing, we'll generally use int, only int, and nothing but int.
  • Conventional: This is a broad, vague everything else category. For most conventional mathematical operations, int, float, and Fraction are all interchangeable. Indeed, a well-written function can often be properly polymorphic; it will work perfectly well with any numeric type. Python types, particularly float and int, will participate in a variety of implicit conversions. This makes the selection of a specific numeric type for these kinds of problems somewhat moot.

These are generally obvious aspects of a given problem domain. It's often easy to distinguish applications that might involve science or engineering and complex numbers from applications that involve financial calculations, currency, and decimal numbers. It's important to be as permissive as possible in the numeric types that are used in an application. Needlessly narrowing the domain of types via the isinstance() test is often a waste of time and code.

In the next section, we'll talk about method resolution and the reflected operator concept.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset