Next: , Previous: , Up: More About Types in Python   [Contents][Index]


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 local-call.) 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.


Next: The Freeze-Type Declaration, Previous: The Values Declaration, Up: More About Types in Python   [Contents][Index]