35

I have a variable "myvar" that when I print out its type(myvar)

the output is:

<class 'my.object.kind'>

If I have a list of 10 variables including strings and variables of that kind.. how can I construct an if statement to check whether an object in the list "mylist" is of <type 'my.object.kind'>?

tobyodavies
  • 27,347
  • 5
  • 42
  • 57
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • It's not clear what you're trying to do. Are you trying to see if the list contains an element of type `my.object.kind`? Are you trying to get the types of all the elements of the list? – user2357112 Aug 08 '13 at 04:09
  • `isinstance()` is the python built-in-function that you're looking for. http://docs.python.org/2/library/functions.html#isinstance – Jonathan Vanasco Aug 08 '13 at 04:14
  • Relevant [What is the difference between type and isinstance](https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance) – snakecharmerb Sep 13 '20 at 15:25

3 Answers3

57

Use isinstance, this will return true even if it is an instance of the subclass:

if isinstance(x, my.object.kind)

Or:

type(x) == my.object.kind #3.x

If you want to test all in the list:

if any(isinstance(x, my.object.kind) for x in alist)
glglgl
  • 89,107
  • 13
  • 149
  • 217
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
  • The post asks for a way to apply this to a list – Owen Aug 08 '13 at 04:08
  • 1
    @zhangyangyu I have `type( x )` that shows `` but then `type( x ) == argparse.Namespace.kind`says `*** AttributeError: type object 'Namespace' has no attribute 'kind'` – SebMa Jun 04 '18 at 13:23
  • @SebMa `my.object.kind` is the class the OP has, not an attribute indicating the type. You should use `type(x) == argparse.Namespace`. – zhangyangyu Jun 05 '18 at 02:58
0
if any(map(lambda x: isinstance(x, my.object.kind), my_list_of_objects)):
    print "Found one!"
Owen
  • 1,726
  • 10
  • 15
0

Try

if any([isinstance(x, my.object.kind) for x in mylist]):
    print "found"
lazy functor
  • 2,118
  • 2
  • 15
  • 16