TypeError: ‘type’ object is not iterable – Iterating over object instances

As far as I can tell, making a class object iterable by using a metaclass works just fine:

from __future__ import print_function

class IterableCar(type):
    def __iter__(cls):
        return iter(cls.__name__)

class Car(object):
    __metaclass__ = IterableCar

    def __init__(self, name):
        self.name = name


if __name__=='__main__':

    car1 = Car('Mercedes')
    car2 = Car('Toyota')
    for cars in Car:
        print (cars)

Results in:

mgilson$ python ~/sandbox/test.py 
C
a
r

Here’s an example where I actually track the cars generated:

from __future__ import print_function
import weakref

class IterableCar(type):

    _cars = weakref.WeakSet()

    def __iter__(cls):
        return iter(cls._cars)

    def add_car(cls, car):
        cls._cars.add(car)


class Car(object):
    __metaclass__ = IterableCar

    def __init__(self, name):
        self.__class__.add_car(self)
        self.name = name


if __name__=='__main__':

    car1 = Car('Mercedes')
    car2 = Car('Toyota')
    for cars in Car:
        print (cars.name)

Note that if you’re using python3.x, to use a metaclass you do:

class Car(metaclass=IterableCar):
    ...

Rather than:

class Car(object):
    __metaclass__ = IterableCar

which likely explains the problem that you’re experiencing

Leave a Comment