Evus Evus - 7 months ago 60
Python Question

Python returning instance of class from list

I try to get index of instance of object in a list. And I don't know how to do it without for-loop.

If someone can show me right direction, without for-looping it.

I find that list has instance of it with any()-function but can't get index out of it.

I try to clarify my problem. If any()-fucntion can find that list(self.data) has instance of object. any()-function returns only true/false. Is there function or way to get index of that instance so i can call it.

And code:

class MyClass:

def __init__(self, f):
self.data = []
self.f = open(f, "rb")
self.mod = sys.modules[__name__]

def readFile(self):
f = self.f
self.head = f.read(8)
while True:
length = f.read(4)
if length == b'':
c = getattr(self.mod, f.read(4).decode())
if any(isinstance(x, c) for x in self.data):
index = self.data.index(c) #Problem is here
self.data[index].append(f.read(int(length.hex(), 16)))
obj = c(data=f.read(int(length.hex(), 16)))
f.read(4) #TODO check CRC


enumerate is the way to go here.

c = getattr(self.mod, f.read(4).decode())
found = [ (i, x) for (i,x) in enumerate(self.data) if isinstance(x, c) ]
if len(found) > 0:
    index, val = found[0]