Improve yield-in-init documentation

This commit is contained in:
Charlie Marsh 2023-02-10 16:47:44 -05:00
parent 98d5ffb817
commit e5f5142e3e
2 changed files with 25 additions and 13 deletions

View File

@ -13,18 +13,24 @@ use crate::{
define_violation!( define_violation!(
/// ### What it does /// ### What it does
/// Checks for `__init__` methods that turned into generators /// Checks for `__init__` methods that are turned into generators by the
/// via the presence of `yield` or `yield from` statements. /// inclusion of `yield` or `yield from` statements.
/// ///
/// ### Why is this bad? /// ### 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 /// ### Example
/// ```python /// ```python
/// class Foo: /// class InitIsGenerator:
/// def __init__(self): /// def __init__(self, i):
/// yield 1 /// yield i
/// ``` /// ```
///
/// ### References
/// * [`py-init-method-is-generator`](https://codeql.github.com/codeql-query-help/python/py-init-method-is-generator/)
pub struct YieldInInit; pub struct YieldInInit;
); );

View File

@ -3,15 +3,21 @@
Derived from the **Pylint** linter. Derived from the **Pylint** linter.
### What it does ### What it does
Checks for `__init__` methods that turned into generators Checks for `__init__` methods that are turned into generators by the
via the presence of `yield` or `yield from` statements. inclusion of `yield` or `yield from` statements.
### Why is this bad? ### 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 ### Example
```python ```python
class Foo: class InitIsGenerator:
def __init__(self): def __init__(self, i):
yield 1 yield i
``` ```
### References
* [`py-init-method-is-generator`](https://codeql.github.com/codeql-query-help/python/py-init-method-is-generator/)