`init` method converted to generatorPYL-E0100
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:
- Remove any
yield
statements from__init__
- 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:
- Trying to implement initialization and iteration in the same method
- Confusing
__init__
with__iter__
- 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 returnNone