Callable design considerations and trade-offs

When designing a callable object, we need to consider the following:

  • The first consideration is the interface of the object. If there's a reason for the object to have a function-like interface, then a callable object is a sensible design approach. Using collections.abc.Callable assures that the callable API is built correctly, and it informs anyone reading the code what the intent of the class is.
  • The secondary consideration is the statefulness of the function. Ordinary functions in Python have no hysteresis – there's no saved state. A callable object, however, can easily save a state. The memoization design pattern makes good use of stateful callable objects.

The only disadvantage of a callable object is the amount of syntax that is required. An ordinary function definition is shorter and therefore less error-prone and easier to read.

It's easy to migrate a defined function to a callable object, as follows:

def x(args): 
    body 

The preceding function can be converted into the following callable object:

class X: 
    def __call__(self, args): 
        body 
x= X() 

This is the minimal set of changes required to get the function to pass unit tests in the new form. The existing body will work in the new context unmodified.

Once the change has been made, features can be added to the callable object's version of the function.

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

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