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!(
/// ### 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;
);

View file

@ -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
```
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/)