paul a écrit :
Bruno Desthuilliers schrieb:
>bg***@yahoo.com a écrit :
>>Hi,
Is it possible to find out if an object is of a certain type or of a
type derived from this type?
You have the answer, thanks to Diez and Christian. Now unless you have
a *very* compelling reason to check the type of an object, *just
forget about it*. 9 times out of 10, this is fighting against the
language's type system (hint: google for "duck typing").
So I have to give up the concept that argument types are part of the
interface or signature?
Nope - you have to give up the notion of type you learned from
statically typed languages, and get used to the one used in dynamically
typed languages. Same word, different concept, really.
Honestly, I don't like that. Granted; not having
strict type checking makes for great flexibility but the price is you
either write typchecking code or let the error propagate into the
function or method.
Just tell me: what will happens if, *in Python*, you "write typechecking
code" ? Surely, when you'll (possibly wrongly[1]) conclude you don't
have the "correct" type (meaning: the one you expected when writing your
code[1]), you'll raise an exception, won't you ? (I can't imagine what
else...). So ask yourself: in which way will the final result be
different from would very probably happens without the "typecheking
code" ? In *both* cases, you end up with a runtime exception.
Granted, without "typechecking", there can be a couple corner cases
where you end up with incorrect results instead of an exception (like
your user passed a string where you expected a sequence which is *not* a
string). These corner cases might be worth the most minimal possible
check. As far as I'm concerned, I've run into this kind of corner case
perhaps half a dozen time in 7+ years. And usually because I (as a user
of someone else's code) failed to read the doc - which is my
responsability, the author's.
[1] dynamic typing means that two totally unrelated types may both
implement the expected (implied) interface. You just can't hope to know
by advance the exhaustive list of classes that will implement the
interface your code expects.
I hope type annotations in py3k will allow for
something like constraints in C# where you can tell the caller right
away she's doing something wrong.
Lord have mercy. As Diez mentions, if you want static type checking,
then don't use a dynamically typed language. But trying to fight against
the language is not going to buy you much.