Evus Evus - 12 days ago 7
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
try:
self.head = f.read(8)
while True:
length = f.read(4)
if length == b'':
break
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)))
else:
obj = c(data=f.read(int(length.hex(), 16)))
self.data.append(obj)
f.read(4) #TODO check CRC
finally:
f.close()

Answer

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]
    ...
Comments