[python] How to check type of object in Python?

I have some value in variable v, how to check it's type?

Hint: it is NOT v.dtype.

When I do type(v) in debugger, I get

type(v) = {type} <type 'h5py.h5r.Reference'>

or

type(v) = {type} <class 'h5py._hl.dataset.Dataset'>

How to check these value at runtime?

"Check" means calculate boolean result, saying if the type is given.

UPDATE

In so called "duplicate" question, it is said, that to compare type one should use

type(v) is str

which implicitly assume that types are strings. Are they?

This question is related to python

The answer is


use isinstance(v, type_name) or type(v) is type_name or type(v) == type_name,

where type_name can be one of the following:

  • None
  • bool
  • int
  • float
  • complex
  • str
  • list
  • tuple
  • set
  • dict

and, of course,

  • custom types (classes)

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).