Why would I use inspect.isclass()?

Nicolas Fleury nid_oizo at yahoo.com_removethe_
Thu Dec 30 01:57:11 EST 2004


It's me wrote:
>>I guess another example would be an assert on the type of argument:
>>def foo(someClass):
>>     assert inspect.isclass(someClass)
>>     # rest of code
>>
> But that would always fail!  (I just tried it).

Are you sure you haven't pass an instance instead of a class?  Remember, 
classes are also objects in Python:

 >>> import inspect
 >>> class A: pass
...
 >>> def foo(a): assert inspect.isclass(a)
...
 >>> foo(A)
 >>>

Works fine and makes sense, no?  Of course, if I pass an instance 
instead of a class it would fail:

 >>> myA = A()
 >>> foo(myA)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 1, in foo
AssertionError

Maybe your question is in what situations passing a class can be useful? 
    There's many examples and once you're used to that capability it can 
be powerful.  One simple example could be the generation of 
documentation; since you usually want to doc your classes, not 
instances.  So it would make sense to do something like:

def writeHtmlDoc(file, someClass): ...

Regards,
Nicolas



More information about the Python-list mailing list