I am looking at methods for detecting the type of a variable (list vs string) within python (2.5+), and came across some other answers which seemed overly convoluted.
I have found one can do
x.__class__.__name__
to get a string containing the class name. What, if anything, is wrong with this? Is it not portable? When would it fail?
The problem is that different classes can have the same name.
The straightforward example is for classes defined in different modules (e.g. think of generic common names such as
Node
orConnection
).However, it's easy to demonstrate this problem even in a single module:
If you don't have to have string-representation of the class, simply use the
type
object returned by callingtype(obj)
.Of course, depending on what you use it for, it might be best to use
isinstance
instead of dealing withtype
objects directly.