Next: 5.3 Type Inference
Up: 5.2 More About Types
Previous: 5.2.10 Type Restrictions
Python provides good support for some currently unconventional ways of
using the Common Lisp type system. With Python, it is desirable to make
declarations as precise as possible, but type inference also makes
some declarations unnecessary. Here are some general guidelines for
maximum robustness and efficiency:
- Declare the types of all function arguments and structure slots
as precisely as possible (while avoiding not, and and
satisfies). Put these declarations in during initial coding
so that type assertions can find bugs for you during debugging.
- Use the member type specifier where there are a small
number of possible symbol values, for example: (member :red
:blue :green).
- Use the or type specifier in situations where the
type is not certain, but there are only a few possibilities, for
example: (or list vector).
- Declare integer types with the tightest bounds that you can,
such as (integer 3 7).
- Define deftype or defstruct types before
they are used. Definition after use is legal (producing no
``undefined type'' warnings), but type tests and structure
operations will be compiled much less efficiently.
- Use the extensions:freeze-type declaration to speed up
type testing for structure types which won't have new subtypes added
later. See section 5.2.9
- In addition to declaring the array element type and simpleness,
also declare the dimensions if they are fixed, for example:
(simple-array single-float (1024 1024))
This bounds information allows array indexing for multi-dimensional
arrays to be compiled much more efficiently, and may also allow
array bounds checking to be done at compile time.
See section 5.10.3.
- Avoid use of the the declaration within expressions.
Not only does it clutter the code, but it is also almost worthless
under safe policies. If the need for an output type assertion is
revealed by efficiency notes during tuning, then you can consider
the, but it is preferable to constrain the argument types
more, allowing the compiler to prove the desired result type.
- Don't bother declaring the type of let or other
non-argument variables unless the type is non-obvious. If you
declare function return types and structure slot types, then the
type of a variable is often obvious both to the programmer and to
the compiler. An important case where the type isn't obvious, and a
declaration is appropriate, is when the value for a variable is
pulled out of untyped structure (e.g., the result of car), or
comes from some weakly typed function, such as read.
- Declarations are sometimes necessary for integer loop variables,
since the compiler can't always prove that the value is of a good
integer type. These declarations are best added during tuning, when
an efficiency note indicates the need.
Next: 5.3 Type Inference
Up: 5.2 More About Types
Previous: 5.2.10 Type Restrictions
Raymond Toy
Mon Jul 14 09:11:27 EDT 1997