1

Because of the yield keyword, the Python compiler understands the method g in the code below as being a generator:

class B(A):
    def g(self):
        yield 1

However, I would like the A base class to provide a default implementation for g producing an empty sequence such as:

list(B().g())
--> [1]

list(A().g())
--> []

To achieve that, I define A as:

class A:
    def g(self):
        return; yield # do NOT remove the yield keyword:
                      # it is necessary for Python to
                      # understand `g` as a generator

It works, but I don't find that very elegant since, barring the comment, it is tempting to remove the unreachable yield statement.

So, is there a better, more pythonic way of defining a generator producing an empty sequence?

Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125

0 Answers0