21

I have some value in variable v, how do I check its type?

Hint: It is NOT v.dtype.

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

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

or

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

How to check these values at runtime?

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

UPDATE

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

type(v) is str

which implicitly assumes that types are strings. Are they?

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

2 Answers2

33

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

Community
  • 1
  • 1
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • Is this true for "class" types also? – Suzan Cioc Feb 18 '16 at 19:36
  • Also in "duplicate" answer it is said to compare with `type(o) is str`. Does this means that types are strings? – Suzan Cioc Feb 18 '16 at 19:38
  • 1
    The ``type(o)`` returns just the class (type) of ``o``. I think it's roughly equivalent to calling ``o.__class__``. – MSeifert Feb 18 '16 at 19:40
  • I don't know what the use-case is but I think one should either use ``isinstance(o, class_to_compare_o_with)`` or ``duck typing``. – MSeifert Feb 18 '16 at 19:42
  • @SuzanCioc: With `type(o) is str` you check whether the object `o` is of the type `str`. If you want to check if it's an integer you would use `type(o) is int`. – Matthias Feb 18 '16 at 20:19
26

Use any of the following:

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

where type_name can be one of:

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

and, of course,

  • custom types (classes)
Henrikh Kantuni
  • 901
  • 11
  • 14
  • 1
    Type comparisons should be done with ``isinstance``. See also https://docs.python.org/2/library/functions.html?highlight=type#type – MSeifert Feb 18 '16 at 20:47