X9BlackHead9X X9BlackHead9X - 10 days ago 4
Python Question

Python : How to know is there is a instantiation of a class in a container?

I am quite new to python, and I haven't figured out yet how to solve my quit simple problem. I did some research, but either I did not found or I didn't understand what to do with it... My question is :
How to know if there is an instanciation of a class in a container such as a list ;
I want to do something like

if class in list :


I know this is a really simple question but to be honest I can't find the proper syntax to make it work :/

Answer

You can use the isinstance built in function to test if an object is an instantiation of a certain class, and the any built in function to test if any of the members of an iterable match your condition:

>>> class A:
        pass

>>> stuff = [1,2,A()]
>>> any(isinstance(a, A) for a in stuff)
True

FYI: all objects in Python are instantiations of some kind of class (even classes themselves!), so there's no point to seeing if an object in a list is an instantiation of any class, since everything in the list will be.

Comments