next up previous contents
Next: The Freeze-Type Declaration Up: 5.2 More About Types Previous: 5.2.7 The Values Declaration

5.2.8 Structure Types

       

Because of precise type checking, structure types are much better supported by Python than by conventional compilers:

This error checking is tremendously useful for detecting bugs in programs that manipulate complex data structures.

An additional advantage of checking structure types and enforcing slot types is that the compiler can safely believe slot type declarations. Python effectively moves the type checking from the slot access to the slot setter or constructor call. This is more efficient since caller of the setter or constructor often knows the type of the value, entirely eliminating the need to check the value's type. Consider this example:

(defstruct coordinate
  (x nil :type single-float)
  (y nil :type single-float))

(defun make-it () (make-coordinate :x 1.0 :y 1.0))

(defun use-it (it) (declare (type coordinate it)) (sqrt (expt (coordinate-x it) 2) (expt (coordinate-y it) 2)))

make-it and use-it are compiled with no checking on the types of the float slots, yet use-it can use single-float arithmetic with perfect safety. Note that make-coordinate must still check the values of x and y unless the call is block compiled or inline expanded (see section 5.6.) But even without this advantage, it is almost always more efficient to check slot values on structure initialization, since slots are usually written once and read many times.



Raymond Toy
Mon Jul 14 09:11:27 EDT 1997