Why would I use inspect.isclass()?

I

It's me

I discovered the hardway what inspect.isclass() is doing. Consider this no
brainer code:

###
import inspect

class Abc:
def Hello(self):
return

an_instance=Abc()
print inspect.isclass(an_instance)
###

It took me a while to understand how I can get inspect.isclass to return a
True (like: inspect.isclass(Abc)).

But what good is that? Of course I know Abc is a class, why would I want to
inspect it so that it would tell me what I already know?

I would have thought this would be the situation I need that for:

###
import inspect

class Abc:
def Hello(self, some_class):
# since I don't know if the argument passed down *is* a class or not, I
would:
if inspect.isclass(some_class)==True:
...
return
###

But that obviously isn't what isclass is for. What should I use?

Thanks,
 
N

Nicolas Fleury

an_instance=Abc()
But what good is that? Of course I know Abc is a class, why would I want to
inspect it so that it would tell me what I already know?

Well, for no reason in that case. For the same reason you would not
call isinstance(an_instance, Abc) if you already know an_instance is an
instance of Abc.
def Hello(self, some_class):
# since I don't know if the argument passed down *is* a class or not, I
would:
if inspect.isclass(some_class)==True:
...
return
###

But that obviously isn't what isclass is for. What should I use?

Well, it's obviously what isclass is for;) (By the way, you would be
better not compare your conditions with True, unless it's really what
you want).

I guess another example would be an assert on the type of argument:
def foo(someClass):
assert inspect.isclass(someClass)
# rest of code

This way errors on types are handled at the beginning and at the same
time the code it documenting itself. The function could also be useful
in cases where you do some C++-like overloading mechanism. Anyway,
isclass, like iscallable, are functions that are not used often, but you
still might need them.

Regards,
Nicolas
 
I

It's me

Nicolas,

Thanks for the response. Please see comment below.

Nicolas Fleury said:
Well, for no reason in that case. For the same reason you would not
call isinstance(an_instance, Abc) if you already know an_instance is an
instance of Abc.


Well, it's obviously what isclass is for;) (By the way, you would be
better not compare your conditions with True, unless it's really what
you want).

But inspect.isclass(some_class) returns a False no matter what. That's why
I am confused.

The only way I get isclass to return True is inspect.isclass(Abc) in my
example.

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).
 
N

Nicolas Fleury

It's me said:
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:

Works fine and makes sense, no? Of course, if I pass an instance
instead of a class it would fail:
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
 
I

it's me

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?
 
N

Nicolas Fleury

it's me said:
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 have the builtin function isinstance:

class A: pass
a = A()
print isinstance(a, A) # True

Regards,
Nicolas
 
?

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

it's me said:
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
False

For many things, it is not obvious that they are classes. For example,
consider str and repr:
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
.... 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
 
S

Steve Holden

it's me said:
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 should Google for "duck typing" and stop worrying so much about what
your functions//methods have been passed.

At least, that's the traditional Python approach. I suspect you are
still trying to program in C in Python :)

regards
Steve
 
S

Steve Holden

Martin said:
it's me said:
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?
[...]

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
.... 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"
....

This technique is often called "introspection", and involves having
programs indulge in the time-honored practice of contemplating their own
navels. The ability to introspect is one side of a major dichotomy in
programming languages. A C program has no real ability to introspect,
but Python and SmallTalk (and Java) programs do.

But it isn't really a novice topic, and many programmers spend entire
careers quite happily without using introspection.

regards
Steve
 
I

It's me

Steve,

You are correct that I worry too much about types. It's *really* hard not
to - having so many years of C in my head (and I am not exactly a
programmer).

I realize that "if you don't understand duck typing, you don't really
understand Python" - and that's why I am struggling to learn about this.

It's hard to writing a routine and not thinking what kind of parameters will
be passed down from above. In the old days, we go out of the way to do that
so programs don't fail in mysterous ways.
 
S

Steve Holden

It's me wrote (top posting as usual, but we won't make a big song and
dance about that[1] :):
Steve,

You are correct that I worry too much about types. It's *really* hard not
to - having so many years of C in my head (and I am not exactly a
programmer).

I realize that "if you don't understand duck typing, you don't really
understand Python" - and that's why I am struggling to learn about this.
Well the basic idea is "treat what you've been passed as though it is
the type you wanted". When it's only you writing the code that's likely
going to be the case. When it's others, you have to be a little more
careful to catch the exceptions (except when you don;t bother, in which
case the users will have to understand the tracebacks).
It's hard to writing a routine and not thinking what kind of parameters will
be passed down from above. In the old days, we go out of the way to do that
so programs don't fail in mysterous ways.
Don't worry. Soon you will understand the Way of Python, and all will
become clear :)

probably-won't-stop-you-top-posting-though-ly y'rs - steve

[1] OK, so I lied.
 
I

It's me

Steve Holden said:
Well the basic idea is "treat what you've been passed as though it is
the type you wanted". When it's only you writing the code that's likely
going to be the case. When it's others, you have to be a little more
careful to catch the exceptions (except when you don;t bother, in which
case the users will have to understand the tracebacks).

I grew up in an environment that believes in prevention, rather then
after-the-fact fixing. That's why it's hard for me to delegate error
checking tasks to exception, rather then assert - it just feel so...."nake".
:=)

Anyway, points taken.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top