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

3

3 Answers 3

58

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)
Sign up to request clarification or add additional context in comments.

3 Comments

The post asks for a way to apply this to a list
@zhangyangyu I have type( x ) that shows <class 'argparse.Namespace'> but then type( x ) == argparse.Namespace.kindsays *** AttributeError: type object 'Namespace' has no attribute 'kind'
@SebMa my.object.kind is the class the OP has, not an attribute indicating the type. You should use type(x) == argparse.Namespace.
0
if any(map(lambda x: isinstance(x, my.object.kind), my_list_of_objects)):
    print "Found one!"

1 Comment

map and lambda are not necessary here, use a generator comprehension.
0

Try

if any([isinstance(x, my.object.kind) for x in mylist]):
    print "found"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.