0

I run python code where i create multiple objects from 1 class and register these object in an IterRegistery:

class IterRegistry(type):
    def __iter__(cls):
        return iter(cls._registry)


class exampleclass(metaclass=IterRegistry):
    _registry = []

    def __init__(self, number):
        self._registry.append(self)
        self.number = number

    def destroy(self):
        if self.number == 1:
            del self


 exampleclass(1)
 exampleclass(2)

 for e in exampleclass:
     e.destroy

Now i would like an object to delist itself from the registery and destroy itself from the inside out if several requirements are met. It tried to do this by using:

del self

But that's not working.

Is there a proper way to achieve this?

  • You have to remove it from the `self._registry` list, I suppose. – mkrieger1 Aug 01 '22 at 10:34
  • Does this answer your question? [Remove object from a list of objects in python](https://stackoverflow.com/questions/9754729/remove-object-from-a-list-of-objects-in-python) – mkrieger1 Aug 01 '22 at 10:37

1 Answers1

1

Remove itsself from the _registry list and python will garbage collect it, and iterate over exampleclass not IterRegistry

class IterRegistry(type):
    def __iter__(cls):
        return iter(cls._registry)


class exampleclass(metaclass=IterRegistry):
    _registry = []

    def __init__(self, number):
        self._registry.append(self)
        self.number = number

    def destroy(self):
        if self.number == 1:
            self.__class__._registry.remove(self)


exampleclass(1)
exampleclass(2)

for e in exampleclass:
    e.destroy()

However you don't need a metaclass:

class exampleclass():
    _registry = []

    def __init__(self, number):
        self._registry.append(self)
        self.number = number

    def destroy(self):
        if self.number == 1:
            self.__class__._registry.remove(self)

    @classmethod
    def __iter__(cls):
        return iter(cls._registry)

exampleclass(1)
exampleclass(2)

for e in exampleclass:
    e.destroy()

or even:

class exampleclass():
    registry = []

    def __init__(self, number):
        self._registry.append(self)
        self.number = number

    def destroy(self):
        if self.number == 1:
            self.__class__._registry.remove(self)

exampleclass(1)
exampleclass(2)

for e in exampleclass.registry:
    e.destroy()
Tom McLean
  • 5,583
  • 1
  • 11
  • 36