Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 321
Suzan Cioc Avatar asked Feb 18 '16 19:02

Suzan Cioc


2 Answers

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

like image 134
MSeifert Avatar answered Oct 28 '22 19:10

MSeifert


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)
like image 43
Henrikh Kantuni Avatar answered Oct 28 '22 20:10

Henrikh Kantuni