What is the class of myobj?

Erik Max Francis max at alcyone.com
Wed Oct 16 03:46:16 CEST 2002

JXStern wrote:

> I want to write something like:
> If ClassOf(myobj) == "MyClass": print "OK!"
>   or
> If ClassOf(myobj) == MyClass: print "OK!"   # no quotes on class
> The best I've found in Python is based on str(myobj.__class__).
> What's the official way?

isinstance(myobj, MyClass)

Though the Pythonic way is to just assume it's got the right interface;
if it doesn't, an error will get raised and you can handle the problem
at that point.

This is particularly important when you're expecting a sequence type,
but there's no convenient test you can use to find _all_ sequence types
(including a user-defined type that implements a sequence interface)
short of just using it and seeing if a problem occurs.

 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Be able to be alone.  Lose not the advantage of solitude.
\__/ Sir Thomas Browne
    Max Pandaemonium / http://www.maxpandaemonium.com/
 A sampling of Max Pandameonium's music.

More information about the Python-list mailing list