how to find out if an object is a class?

Ben Finney bignose+hates-spam at benfinney.id.au
Thu Aug 7 19:50:04 EDT 2008


szczepiq <szczepiq at gmail.com> writes:

> Pardon me for most likely a dummy question but how do I find out if
> an object is a class?

You can test using 'isinstance'. However, using that is a bad code
smell, which requires investigation as to the reason.

Presumably you want to know whether it's a class in order to use it
for instantiating it. It is usually more Pythonic to use the object as
intended, and allow the object itself to tell you (via exceptions)
when it's not behaving as you expect.

    >>> def foo(spam_class):
    ...     spam_arg = 10
    ...     spam_instance = spam_class(spam_arg)
    ...     # … do stuff with spam_instance …
    ... 
    >>> foo(int)
    >>> foo("not a class")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in foo
    TypeError: 'str' object is not callable

> I need something like that:
> 
> def foo(self, obj):
>   if (obj is a class):
>     some stuff

Why do you think you need to test whether an object is a class? What
problem are you trying to solve?

-- 
 \                “I got fired from my job the other day. They said my |
  `\          personality was weird. … That's okay, I have four more.” |
_o__)                                       —Bug-Eyed Earl, _Red Meat_ |
Ben Finney



More information about the Python-list mailing list