Functional Python Programming

(Wang) #1

The Functools Module


Since Python Numbers class is intended to be immutable, ordinary functional design
can be applied to all of the various method functions. The exceptional Python in-
place special methods (for example, iadd() function) can be simply ignored.


When working with subclasses of Number, we have a fairly extensive volume of
design considerations as follows:



  • Equality testing and hash value calculation. The core features of hash
    calculation for numbers is documented in the 9.1.2 Notes for type implementors
    section of the Python Standard Library.

  • The other comparison operators (often defined via @total_ordering
    decorator).

  • The arithmetic operators: +, -, *, /, //, %, and **. There are special methods
    for the forward operations as well as additional methods for reverse type-
    matching. Given an expression like a-b, Python uses the type of a to attempt
    to locate an implementation of the sub() method function: effectively, the
    a.sub(b) method. If the class of the left-hand value, a in this case, doesn't
    have the method or returns the NotImplemented exception, then the right-
    hand value is examined to see if the b.rsub(a) method provides a result.
    There's an additional special case that applies when b's class is a subclass of a's
    class: this allows the subclass to override the left-hand side operation choice.

  • The bit-fiddling operators: &, |, ^, >>, <<, and ~. These might not make
    sense for floating-point values; omitting these special methods might be
    the best design.

  • Some additional functions like round(), pow(), and divmod() are
    implemented by numeric special method names. These might be meaningful
    for this class of numbers.


Chapter 7, Mastering Object-Oriented Python provides a detailed example of creating
a new type of number. Visit the link for more details:


https://www.packtpub.com/application-development/mastering-object-
oriented-python.


As we noted previously, functional programming and object-oriented programming
can be complementary. We can easily define classes that follow functional
programming design patterns. Adding new kinds of numbers is one example of
leveraging Python's object-oriented features to create more readable functional
programs.

Free download pdf