[Tutor] simple question about numeric types
Kent Johnson
kent37 at tds.net
Tue May 9 02:26:06 CEST 2006
Emanuele Rocca wrote:
> Hello list,
> I've got a question partially related to this thread.
>
> * Gregor Lingl <glingl at aon.at>, [2006-05-03 0:24 +0200]:
>> v=<some numeric value>
>> if isinstance(v, int) or isinstance(v, float):
>> <block>
>
> I wonder which is the recommended way to check the type of a value.
Often the recommendation is just to assume that a value is the correct
type and be ready to catch an exception if it is not. This allows 'duck
typing' to work - your function (or whatever) will accept any value that
implements the correct methods, whether it has a particular inheritance
relationship with the expected type or not. For example you could make a
function that accepted any mapping object whether it inherits from dict
or not.
>
> In other words, what should I choose between:
> isinstance(v, int)
This is good because it will accept subclasses of int as well as plain
ints. (Not that subclasses of int are that common, but other classes
might be subclassed.)
> type(v) is int
> v.__class__ is int
I think these are equivalent, though I would prefer the first. They are
the most restrictive choice because they require an exact class match.
Kent
>
> There's simply more than one way to do it or some of them are
> discouraged?
>
> I've been told on #python that .__class__ is probably the worst one, but
> without precise motivation, just as a personal opinion.
>
> ciao,
> ema
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list