As a part of memoizing mechanism, I have a generator, I tee
it, and I need to check its type with isinstnace
.
>>> gen = (i for i in range(5))
>>> one, two = itertools.tee(gen, 2)
then
>>> type(one), type(two)
(itertools.tee, itertools.tee)
as expected, but
>>> isinstance(one, itertools.tee)
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
so what is the instance of tee
?
Let's say we define a class MyClass
:
class MyClass(object):
pass
We then define a function that overrides that class:
def MyClass(x=MyClass):
return x()
If we call that function, we will get an instance of the original MyClass
:
>>> instance = MyClass()
>>> type(instance)
<class '__main__.MyClass'>
It looks like MyClass
is a class because the type of its return value has the same name, but take a look:
>>> type(MyClass)
<type 'function'>
MyClass
is a function that returns an instance of MyClass
, but they are different. It is the same thing with tee
. tee
is a function that returns an instance of tee
. When you see if that instance is of type tee
, you aren't actually checking a class or a type; you are checking a function. isinstance()
will not allow that, so hence the error. The way to get the class would be to create an instance:
>>> tee = type(itertools.tee(())[0])
>>> isinstance(one, tee)
True