A little stricter type checking
adalke at mindspring.com
Sun Sep 5 07:57:34 CEST 2004
Peter Otten wrote:
> There are at least three more idioms that could (sometimes) be replaced
> by type-checking:
Though from what I can tell the OP wanted "real" type
checking, as found in Java and C. The original text was
] On the other hand in languages like C, java etc...
] where types are strict we have the guarantee that
] the variables will always be the same type without
] any change.
> # "casting"
Wouldn't that be type conversion, and not a check?
> # check for an "interface"
> lower = s.lower
> except AttributeError:
> raise TypeError
Mmm, there's a problem with this checking. Consider
lower = 8
Though the odds are low.
> # check for an "interface", LBYL-style
> if not hasattr(foo, "bar"):
> raise TypeError
Aren't both of these the "look before you leap" style?
Well, except for checking for the callable.
> These are more difficult to hunt and I'm lazy.
> However, I don't think you can tell from the structure alone whether an
> explicit type declaration would be a superior solution in these cases.
I do at times use tests like you showed, in order
to get a more meaningful error message. I don't
think they are considered type checks -- perhaps
protocol checks might be a better term?
> Should Python be extended to allow type declarations, I expect them to
> appear in places where they reduce the usefulness of the code while
> claiming to make it safe...
As was mentioned in the @PEP (as I recall) one of the
interesting possibilities is to use type checks with
support for the adapter PEP so that inputs parameters
can get converted to the right type, rather like your
As new image data types are added, they can be passed to
draw() without need for an explicit convert step, so
long as the adapter is registered.
dalke at dalkescientific.com
More information about the Python-list