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

Gustavo Cordova gcordova at hebmex.com
Wed Feb 6 14:25:31 EST 2002


NO NO NO NO NO NO!!!

**WHY*** do you want to break beautiful OO-code with this?

> $ python
> >>> import types
> >>> l = []
> >>> if type(l) == types.ListType:
> ...     print "yeah baby!"
> ...
> yeah baby!

Or with this??
> or better:
>    if type(l) is types.ListType:
>        ...
> or even better:
>    if isinstance(l, types.ListType):
>        ...
> or, in 2.2 or later:
>    if isinstance(l, list):
>        ...

What if I pass an instance of an object which
behaves like an array? This code will surely
break, uglily [sp].

So, yes, you *can* identify when an object
is descendant of types.ListType, or or list
in case of Python 2.2, but that'll limit
your code's functionality.

Alas, I don't have an answer to your question,
besides checking if your received object has
a __getitem__ and __len__ method.

Sorry.

-gus




More information about the Python-list mailing list