473,320 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Why would I use inspect.isclass()?

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
11 3914
> 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
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
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
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
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
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
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
Martin v. Löwis 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
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
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

"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Hans Georg Krauthaeuser | last post by:
Dear all, I have a problem to get the command that has called a function if the command was given on multiple lines. E.g.: ################################################### import inspect ...
1
by: Thomas Guettler | last post by:
Hi, the line numbers of inspect.getinnerframes are different from traceback.format_exception. This results in wrong lines being shown in cgitb. An example is below. I looked at the...
2
by: Fernando Perez | last post by:
Hi all, IPython has suffered quite a few problems with the inspect module in python 2.3. For these, unfortunately all I've been able to do is guard with overreaching except clauses, as I had...
4
by: Benjamin Rutt | last post by:
I'm trying to learn about introspection in Python. my ultimate goal is to be able to build a module "text database" of all modules that are in the sys.path, by discovering all candidate modules...
0
by: Ron Adam | last post by:
While playing around with the inspect module I found that the Blockfinder doesn't recognize single line function definitions. Adding the following two lines to it fixes it, but I'm not sure if it...
1
by: aj | last post by:
What is the difference (if any) between inspect check database and db2dart ??? Do they both find the same potential problems? Does one provide more comprehensive checking than the other? ...
4
by: Chris Pax | last post by:
Hello, I recently been trying to use the inspect module to inspect the arguments of gtk objects, such as gtk.Button. I tried like this: inspect.getargspec(gtk.Button.__init__) and get the...
8
by: Aaron \Castironpi\ Brady | last post by:
Hello, The 'inspect' module has this method: inspect.getargvalues(frame) It takes a frame and returns the parameters used to call it, including the locals as defined in the frame, as shown....
0
by: rajasankar | last post by:
Hi, I am using Jython based application and trying to use inspect.py in the python files. Here is my code import inspect,os,sys,pprint,imp def handle_stackframe_without_leak(getframe): ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.