testing for class of instance

Stephen Hansen news at myNOSPAM.org
Sun May 13 02:10:56 EDT 2001


    Your example doesn't exactly follow your question. To determine if a
perticular object is the instance of a perticular class, you can use the
isinstance() function... your example, though, wishes to check for the type
of an object, which is unfortunately a different issue.

    from types import *

    if type(object) is DictType:

is the correct way to test if an object is a dictionary, which is what your
example wants to do.

    But, really, in almost all circumstances, you don't want to do either of
these things, IMHO. It should not matter to you if you are being passed a
true dictionary, a UserDict, or a dictionary-like wrapper around a
distributed database running over a Carrier Pigeon Transport.

    All that should matter to you is that the object *acts* like a
dictionary. You limit the ability of your program to be customized and
extended by enforcing types strictly; let Python's polymorphism work for
you. Instead of checking to see if an object is of a type, or of a
perticular class, just try to _use_ the class, and if it works, continue.
For example:

def printname(object):
    try:
        print 'My name is ', object[name]
    except TypeError, AttributeError:
        print 'You didn't send me a dictionary-like object!'

    BTW. The reason that you have to catch TypeError and AttributeError is
because of the difference between classes and types above: list['name'] or
5['name'] will raise a TypeError, while class['name'] will raise an
AttributeError if it does not support the dictionary-like interface provided
through __getitem__.

HTH,

--Stephen
(replace 'NOSPAM' with 'seraph' to respond in email)

"Albert Wagner" <alwagner at tcac.net> wrote in message
news:tfrvnd6dhd174b at corp.supernews.com...
> How do I test for the class of an instance?  e.g., I used to test for a
> dictionary:
>
> if type(aContainer) == type({}):
>
> However, this seems awkward and wasteful.





More information about the Python-list mailing list