mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-04 02:38:25 +00:00
Improve yield-in-init documentation
This commit is contained in:
parent
98d5ffb817
commit
e5f5142e3e
2 changed files with 25 additions and 13 deletions
|
@ -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;
|
||||
);
|
||||
|
||||
|
|
|
@ -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/)
|
Loading…
Add table
Add a link
Reference in a new issue