2

Why does inspect.isgenerator() return false for this class generator definition (working in python 3.7)?

I know that isgenerator is checking weather the object is of type

"generator" 

and my class is of type

"__main__.generator" 

which I don't know why. How do I make it of type "generator"? (I need this because of some other 3rd library which is checking this).

class generator(object):
  def __init__(self):
    pass
  def __getitem__(self, index):
    return [0,0]

  def __iter__(self):
    return self  

  def __next__(self):
    return [0,0]

  def next(self):
      return self.__next__()  

a = generator()

import inspect
print(inspect.isgenerator(a))
print(type(a))

thanks for help!

GpG
  • 502
  • 5
  • 11
  • @MadPhysicist: Unduping because implementing the rest of the generator API won't do anything to make a class pass `inspect.isgenerator`. – user2357112 Oct 25 '19 at 11:08

2 Answers2

3

"Generator" is a specific built-in type, and your type will never be that type, no matter what methods you implement or what name you give it. You cannot make instances of your class be actual generators. (Not even through subclassing - the real generator type cannot be subclassed.) Also, generators have send and throw methods used for coroutine functionality, but it doesn't make sense for your class to have those, and implementing them still won't make your objects pass inspect.isgenerator.

inspect.isgenerator is intended to check for an actual generator, not arbitrary iterators or objects mimicking generators.

If the third-party library you're using needs a real generator, you will have to give it an actual generator, by writing and calling a generator function, or by writing a generator expression.

If the third-party library doesn't actually need anything generator-specific, you could file an issue asking that they switch to a less restrictive check than inspect.isgenerator.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

Generator cant be subclassed. If you just want to pass the test inspect.isgenerator add to your class:

import types
class generator(object):
    ...
    @property
    def __class__(self):
        # maybe condition with caller
        return types.GeneratorType

...
print(inspect.isgenerator(a)) # True
T'East
  • 79
  • 1
  • 3
  • 1
    I specifically avoided putting anything like this in my answer, because it's more likely to cause problems than to solve them. – user2357112 Oct 25 '19 at 18:03