By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

Why would I use inspect.isclass()?

P: n/a
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,
Jul 18 '05 #1
Share this Question
Share on Google+
11 Replies


P: n/a
> 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
Jul 18 '05 #2

P: n/a
Nicolas,

Thanks for the response. Please see comment below.

"Nicolas Fleury" <ni******@yahoo.com_removethe_> wrote in message
news:as********************@weber.videotron.net...
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).


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

Jul 18 '05 #3

P: n/a
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
Jul 18 '05 #4

P: n/a
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?

--
It's me

"Nicolas Fleury" <ni******@yahoo.com_removethe_> wrote in message
news:kD********************@weber.videotron.net...
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

Jul 18 '05 #5

P: n/a
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 have the builtin function isinstance:

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

Regards,
Nicolas
Jul 18 '05 #6

P: n/a
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
Jul 18 '05 #7

P: n/a
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 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
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #8

P: n/a
Martin v. Lwis wrote:
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?

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


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
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #9

P: n/a
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.
"Steve Holden" <st***@holdenweb.com> wrote in message
news:0ATAd.63675$Jk5.14829@lakeread01...
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 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
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119

Jul 18 '05 #10

P: n/a
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.
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #11

P: n/a

"Steve Holden" <st***@holdenweb.com> wrote in message
news:ecXAd.64160$Jk5.21357@lakeread01...
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.
Jul 18 '05 #12

This discussion thread is closed

Replies have been disabled for this discussion.