Next: The Freeze-Type Declaration
Up: More About Types in
Previous: The Values Declaration
  Contents
  Index
Structure Types
structure types
defstruct types
structure
Because of precise type checking, structure types are much better supported by
Python than by conventional compilers:
- The structure argument to structure accessors is precisely
checked--if you call foo-a on a bar, an error
will be signaled.
- The types of slot values are precisely checked--if you pass
the wrong type argument to a constructor or a slot setter, then an
error will be signaled.
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 usesingle-float arithmetic with perfect safety. Note thatmake-coordinate must still check the values of x andy unless the call is block compiled or inline expanded
(see section 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
Up: More About Types in
Previous: The Values Declaration
  Contents
  Index
Peter Van Eynde
2001-03-08