How to check if variable is a specific class in python?
Question:
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'>
?
Answers:
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)
if any(map(lambda x: isinstance(x, my.object.kind), my_list_of_objects)):
print "Found one!"
Try
if any([isinstance(x, my.object.kind) for x in mylist]):
print "found"
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'>
?
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)
if any(map(lambda x: isinstance(x, my.object.kind), my_list_of_objects)):
print "Found one!"
Try
if any([isinstance(x, my.object.kind) for x in mylist]):
print "found"