Python - Generator case where nothing to return

for-loop, generator, python

Solution

Just do a simple check:

def iterate_my_objects_if_something(self):
    if self.my_objects:
        for x in self.my_objects:
            if x.something:
                yield x

Problem

I have a generator like so: ``` def iterate_my_objects_if_something(self): for x in self.my_objects: if x.something: yield x ``` Which I call like so: ``` for x in self.iterate_my_objects_if_something(): pass ``` In the case where there is nothing to return, this tries to iterate over NoneType and throws an exception. How do I return an empty generator instead?

Original source

Related problems