22

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?

4
  • 4
    What do you mean by "check"? Do you want to print the type name? Do you want to compare the type to some known type? Commented Feb 18, 2016 at 19:16
  • I want to compare to this type next time. Commented Feb 18, 2016 at 19:23
  • Re: "UPDATE". No, types are not strings, nor does the duplicate answer imply that they are. Commented Feb 18, 2016 at 19:58
  • 3
    What "str" may mean then? Straightrunning? Stride? May be Stradivarius? Commented Feb 18, 2016 at 20:13

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Is this true for "class" types also?
Also in "duplicate" answer it is said to compare with type(o) is str. Does this means that types are strings?
The type(o) returns just the class (type) of o. I think it's roughly equivalent to calling o.__class__.
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.
@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.
28

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)

1 Comment

Type comparisons should be done with isinstance. See also docs.python.org/2/library/functions.html?highlight=type#type

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.