Yann Kull
Yann Kull

Reputation: 51

Object not iterable in python when created made class iterable for objects

I am making a program where I need to iterate through every option in a class to perform actions to each object, to do that I made an 'IterRegistry' Class to turn the metaclass of my objects to iterable but for some reason, it still isn't working.

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


class TreeLine(object):
    __metaclass__ = IterRegistry
    _registry = []

    def __init__(self, earnings, buy_price):
        self._registry.append(self)
        self.earnings = earnings
        self.buy_prince = buy_price


TreeLine(0, 0)
TreeLine(0, 7)

for i in TreeLine:
    print(i)

I just get the error message: File "/Users/PycharmProjects/AISTUFF/venv/[email protected]", line 23, in for i in TreeLine: TypeError: 'type' object is not iterable

Upvotes: 0

Views: 1550

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55933

Declaring a class metaclass like this:

class TreeLine(object):
    __metaclass__ = IterRegistry

does not work in Python 3. Instead, the metaclass is declared like this:

class TreeLine(metaclass=IterRegistry):
    ...

The syntax is documented here. The change was proposed in PEP3115.

Note that the __metaclass__ form is not invalid syntax, it just doesn't behave as in Python 2.

>>> class M(type):pass
... 
>>> class C:
...     __metaclass__ = M
... 
>>> type(C)
<class 'type'>
>>> class D(metaclass=M):pass
... 
>>> type(D)
<class '__main__.M'>
>>> 

Upvotes: 1

Related Questions