Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if variable is a specific class in python?

Tags:

python

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'>?

like image 856
Rolando Avatar asked Aug 08 '13 04:08

Rolando


People also ask

How do you check if a variable is of a certain type?

Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.

How do you check if something is a certain type in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.


1 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) 
like image 115
zhangyangyu Avatar answered Oct 05 '22 16:10

zhangyangyu