diff --git a/crates/ruff/src/rules/pylint/rules/yield_in_init.rs b/crates/ruff/src/rules/pylint/rules/yield_in_init.rs index 93cbc3d617..5f73f4de52 100644 --- a/crates/ruff/src/rules/pylint/rules/yield_in_init.rs +++ b/crates/ruff/src/rules/pylint/rules/yield_in_init.rs @@ -13,18 +13,24 @@ use crate::{ define_violation!( /// ### What it does - /// Checks for `__init__` methods that turned into generators - /// via the presence of `yield` or `yield from` statements. + /// Checks for `__init__` methods that are turned into generators by the + /// inclusion of `yield` or `yield from` statements. /// /// ### Why is this bad? - /// Generators are not allowed in `__init__` methods. + /// The `__init__` method of a class is used to initialize new objects, not + /// create them. As such, it should not return any value. By including a + /// yield expression in the method turns it into a generator method. On + /// calling, it will return a generator resulting in a runtime error. /// /// ### Example /// ```python - /// class Foo: - /// def __init__(self): - /// yield 1 + /// class InitIsGenerator: + /// def __init__(self, i): + /// yield i /// ``` + /// + /// ### References + /// * [`py-init-method-is-generator`](https://codeql.github.com/codeql-query-help/python/py-init-method-is-generator/) pub struct YieldInInit; ); diff --git a/docs/rules/yield-in-init.md b/docs/rules/yield-in-init.md index 83bbb585a7..768cbd0a7e 100644 --- a/docs/rules/yield-in-init.md +++ b/docs/rules/yield-in-init.md @@ -3,15 +3,21 @@ Derived from the **Pylint** linter. ### What it does -Checks for `__init__` methods that turned into generators -via the presence of `yield` or `yield from` statements. +Checks for `__init__` methods that are turned into generators by the +inclusion of `yield` or `yield from` statements. ### Why is this bad? -Generators are not allowed in `__init__` methods. +The `__init__` method of a class is used to initialize new objects, not +create them. As such, it should not return any value. By including a +yield expression in the method turns it into a generator method. On +calling, it will return a generator resulting in a runtime error. ### Example ```python -class Foo: - def __init__(self): - yield 1 -``` \ No newline at end of file +class InitIsGenerator: + def __init__(self, i): + yield i +``` + +### References +* [`py-init-method-is-generator`](https://codeql.github.com/codeql-query-help/python/py-init-method-is-generator/) \ No newline at end of file