What is the command to determine an object's type?

Christian Tanzer tanzer at swing.co.at
Thu Feb 7 03:18:03 EST 2002


Tino Lange <tl_news at nexgo.de> wrote:

> On Tue, 05 Feb 2002 22:38:49 GMT, "Fredrik Lundh"
> <fredrik at pythonware.com> wrote:
>
> Hi Fredrik!
>
> (1) if type(l) == types.ListType:
> >or better:
> (2) if type(l) is types.ListType:
> >or even better:
> (3) if isinstance(l, types.ListType):
>
> Why is "if isinstance(l, types.ListType):" even better than the rest?
> What do you mean by "better"?
>
> I just compared the speed of execution (using Python 2.1 on Linux) and
> found consistently:
> (2) is the fastest, the comes (3), (1) is much slower.

This has nothing to do with speed [*]. (3) will work for subtypes of
list, too -- by using (2) you are breaking polymorphism.

As others already pointed out, even (3) is generally a bad idea (TM).
Using any kind of type checking reduces the reusability of your code.
While (3) is definitely better than (1) or (2), it still breaks
signature based polymorphism.

[*] As Qualtinger said in `Da Wüüde auf sana Maschin`: `I woaß zwoa näd
    wohin, oba dafur bin i schnölla durt` <wink>

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92






More information about the Python-list mailing list