Why would I use inspect.isclass()?

"Martin v. Löwis" martin at v.loewis.de
Thu Dec 30 10:45:03 CET 2004


it's me wrote:
> Okay, Nick, I didn't know you can pass a "Class" rather then an instance.  I
> have to chew on what your example does.
> 
> But no, I want to pass an instance of a Class.  But how do I know that the
> calling routine *did* pass me a class - pardon me: an instance of a Class?

You really need to fully digest the difference between classes and
instances. In Python, both classes and instances (of classes) are
objects/values (just like functions and modules). You can bind (store)
*classes* in variables, like so

 >>> import httplib
 >>> x=httplib.HTTP
 >>> inspect.isclass(x)
True
 >>> x=3
 >>> inspect.isclass(x)
False

For many things, it is not obvious that they are classes. For example,
consider str and repr:

 >>> inspect.isclass(repr)
False
 >>> inspect.isclass(str)
True

Actually, in older Python versions, str was not always a class (a type).
It used to be a function, but now is a class.

The real purpose of why you have *inspect*.isclass is for inspecting.
For example, assume I wanted to display the contents of module httplib.
I would need to find out what the things in httplib are, and I do this
with

 >>> for x in dir(httplib):
...   print x,
...   x = getattr(httplib, x)
...   if inspect.isclass(x):print "class"
...   elif inspect.isfunction(x):print "function"
...   elif inspect.ismodule(x):print "module"
...   else: print "something else"
...
BadStatusLine class
CannotSendHeader class
CannotSendRequest class
FakeSocket class
HTTP class
HTTPConnection class
HTTPException class
HTTPMessage class
HTTPResponse class
HTTPS class
HTTPSConnection class
HTTPS_PORT something else
HTTP_PORT something else
ImproperConnectionState class
IncompleteRead class
InvalidURL class
LineAndFileWrapper class
NotConnected class
ResponseNotReady class
SSLFile class
SharedSocket class
SharedSocketClient class
StringIO something else
UnimplementedFileMode class
UnknownProtocol class
UnknownTransferEncoding class
_CS_IDLE something else
_CS_REQ_SENT something else
_CS_REQ_STARTED something else
_UNKNOWN something else
__all__ something else
__builtins__ something else
__doc__ something else
__file__ something else
__name__ something else
errno module
error class
mimetools module
socket module
test function
urlsplit function

Regards,
Martin



More information about the Python-list mailing list