Can I check if an item in a list is a specific type of object?

Hi,

I am making code for a smarthome-application. I have different classes (house, room, smartdevices,…) Every room has a list with all the smartdevices in that specific room. Is there a way to check if a smartdevice in that list is a specific object-type? For example, can I check if a ‘device’ in my list is of the objecttype ‘Lamp’ so if movement is detected in the room, the sensor kan give a sign to the device of type ‘Lamp’ to switch on.

So there are a couple of ways you can do this:

class Item1:
    def __init__(self, val=1):
            self.val =  val

class Item2:
    ...


items = [Item1(), Item2(), Item1(23)]

for item in items:
    print(isinstance(item, Item1)) # Outputs True for the first one, False for the second, True for the third.

for idx, item in enumerate(items):
    match item:
        case Item1():
            print(f'Item at index {idx} is Item1')
        case Item2():
            print(f'Item at index {idx} is Item2')
# Output of second loop:
# Item at index 0 is Item1
# Item at index 1 is Item2
# Item at index 2 is Item1

Thank you!
isinstance was exactly what I needed!

1 Like