liv2hak liv2hak - 1 year ago 93
Python Question

Checking if a class is iterable

I have a class

given below. It implements
. It is an iterable as well as its own iterator.

class fib(object):
def __init__(self):
self.prev = 0
self.curr = 1

def __iter__(self):
return self

def __next__(self):
value = self.curr
self.curr += self.prev
self.prev = value
return value

from collections import Iterable

print(isinstance(fib, Iterable))

The print statement returns
, I would expect it to return

Answer Source

You're supplying a class to isinstance not an instance. It's False because isinstance will go ahead and check if type(fib) has an __iter__ method defined:

# type(fib) is type, its default metaclass, doesn't define __iter__
type(fib).__iter__  # AttributeError

Supply an instance to it and print yields True:

isinstance(fib(), Iterable)  # True

Alternatively, feed fib to issubclass for a similar check that takes a class as a first arg.

issubclass(fib, Iterable)    # True

Two extra things to point out:

  • Using object explicitly is unnecessary in Python 3 (good to use if you're developing code that runs on both Py2 and Py3, though)
  • According to PEP 8, class names should be capitalized so fib -> Fib.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download