Python from Wise Guy's Viewpoint

Lex Spoon lex at cc.gatech.edu
Thu Oct 30 18:37:05 EST 2003


Fergus Henderson <fjh at cs.mu.oz.au> writes:
>>Why? If the collection happens to contain only elements of a single type 
>>(or this type at most), you only need to check write accesses if they 
>>violate this condition. As long as they don't, you don't need to check 
>>read accesses.
>
> So which, if any, implementations of dynamic languages actually perform such
> optimizations?


I'm sure every implementation does this "optimization", because it is
simply less code.  The only time you get a dynamic type error are:

       1. You try to call a method, but the object has no such method.

       2. You call a primitive function or method, and the primitive
       balks.  (This would include trying to write a string into an
       array-of-byte.)


I suppose you could add this one, which also applies to statically
typed languages:

      3. The code explicitly checks for type information.


If you are simply doing "x := y" then there is no checking required.


Regarding your earlier question, though, the great trick in Self was
to remember the result of a check and thus avoid doing it again
whenever possible.  If you do "y := x + 1", and you determine that "x"
is a floating point number, then you know that "y" will also be a
floating point number immediately afterwards.


This points to a general observation.  Dealing with the #1 style
dynamic type errors is a subset of dealing with dynamic dispatch in
general.  If you try to execute "x + 1" or "(foo data-structure)", you
will need to locate which "+" method or which branch of foo's case
statement to execute.  A dynamic type error means that you decide
to use method "typeError" or branch "type error".  Furthermore, any
optimizations that get rid of these dynamic lookups, will also get
rid of type checks just by their nature.  If "x + 1" always uses the
floating-point "+", then clearly it cannot ever use the "typeError" 
version of "+".


-Lex





More information about the Python-list mailing list