Python logoPython/
PYL-E0100

`init` method converted to generatorPYL-E0100

Critical severityCritical
Bug Risk categoryBug Risk

The __init__ method contains a yield statement, which converts it into a generator function. This is not allowed as __init__ must return None. Any attempt to use yield in __init__ will raise a TypeError.

The __init__ method is a special method in Python classes that initializes new instances. It has strict requirements:

  • Must return None (implicitly or explicitly)
  • Cannot be a generator function (no yield statements)
  • Cannot return any other value

Here's an example of incorrect usage:

class DataProcessor:
    def __init__(self, data):
        self.data = data
        yield from self.process_data()  # TypeError: __init__() should return None

    def process_data(self):
        for item in self.data:
            yield item * 2

To fix this, you should:

  1. Remove any yield statements from __init__
  2. Move generator functionality to a separate method

Here's the corrected version:

class DataProcessor:
    def __init__(self, data):
        self.data = data
        # Initialize only, no generators

    def process_data(self):
        # Generator functionality belongs in a separate method
        for item in self.data:
            yield item * 2

# Usage
processor = DataProcessor([1, 2, 3])
for result in processor.process_data():
    print(result)  # Outputs: 2, 4, 6

Common mistakes that lead to this error:

  1. Trying to implement initialization and iteration in the same method
  2. Confusing __init__ with __iter__
  3. Attempting to make the class itself iterable through __init__

If you need to make your class iterable, use the appropriate special methods instead:

class IterableDataProcessor:
    def __init__(self, data):
        self.data = data  # Clean initialization

    def __iter__(self):
        # Generator functionality belongs here
        for item in self.data:
            yield item * 2

# Now the class itself is iterable
processor = IterableDataProcessor([1, 2, 3])
for result in processor:
    print(result)  # Outputs: 2, 4, 6

Remember:

  • __init__ is for initialization only
  • Use __iter__ for making a class iterable
  • Generator functionality should be in separate methods
  • __init__ must implicitly or explicitly return None

References: