liv2hak liv2hak - 14 days ago 5
Python Question

Checking if a class is iterable

I have a class

fib
given below. It implements
__iter__
and
__next__
. 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
False
, I would expect it to return
True

Answer

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