liveBook · Manning

Lazy evaluation

As explained in Software Design for Python Programmers

The Lazy Evaluation Principle postpones a calculation until its result is required, particularly when the calculation is expensive or time-consuming.

Lazy evaluation postpones an expensive calculation until its result is needed. A hybrid Date representation stores year-month-day values and Julian day numbers, converting between them only when a getter or date-arithmetic method requires the corresponding form. section 5.3.3

The Date implementation applies the technique through synchronized representations:

  • Getters validate the year-month-day representation before returning year, month, or day. section 5.3.3
  • Date arithmetic validates the Julian representation before adding days or calculating differences. section 5.3.3
  • Validity flags prevent repeated conversions after a representation has been synchronized. section 5.3.3
Listing 5.12 (Program 5.4 DateArithmetic-3): date.py (1 of 2; efficient hybrid)
class Date:
    ...
    def __init__(self, *parms):
        if len(parms) == 1:
            self._julian = parms[0]    #1
            self._ymd_valid = False     #1
            self._julian_valid = True     #1
        else:
            self._year, self._month, self._day = parms    #2
            self._ymd_valid = True     #2
            self._julian_valid = False     #2

    def _validate_ymd(self):    #3
        if not self._ymd_valid:
            self._year, self._month, self._day = \
                                    Date._to_ymd(self._julian)
            self._ymd_valid = True

    def _validate_julian(self):    #4
        if not self._julian_valid:
            self._julian = \
                Date._to_julian(self._year, self._month, self._day)
            self._julian_valid = True

Inspect the validation methods that convert representations only when their values become necessary. section 5.3.3

How Software Design for Python Programmers covers it

How deep it goes
Explains deferred conversion, synchronized representations, validity flags, and encapsulated access, without detailing conversion algorithms.
Examples
Uses a Date class whose getters validate year-month-day values while arithmetic methods validate Julian day numbers.
What it assumes
Assumes familiarity with object state, properties, encapsulation, and maintaining multiple representations of a value.
What you can do after
Apply it by guarding expensive conversions with validity checks and triggering them at the first operation that needs their results.
How it connects
Connects lazy evaluation with encapsulation, properties, object state, date arithmetic, and Julian day numbers.

Also explained in

Compare how 13 books explain lazy evaluation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.