-
-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: implement new TRY005 violation
- Loading branch information
1 parent
bc6d757
commit 5b65dc3
Showing
11 changed files
with
211 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
# `TRY005` - Define `__reduce__` to make exception pickable | ||
|
||
## Why is it bad | ||
|
||
When using multiprocessing (or anything that serializes with Pickle), and you raise an exception [Pickle uses `__reduce__`](https://docs.python.org/2/library/pickle.html#object.__reduce__) to serialize it. | ||
|
||
It breaks if your exception takes custom args (not string or not optional). | ||
|
||
[Stack Overflow question](https://stackoverflow.com/questions/16244923/how-to-make-a-custom-exception-class-with-multiple-init-args-pickleable) | ||
|
||
## How to enable it | ||
|
||
Since not every project would care about it, this is an optional violation that can be enabled through `check_pickable`. | ||
|
||
## How it looks like | ||
|
||
```py | ||
class ManyArgsMissingReduce(Exception): | ||
def __init__(self, val1: str, val2: str) -> None: # Requires pickable | ||
super().__init__(f"{val1} {val2}") | ||
|
||
|
||
class CustomMissingReduce(Exception): | ||
def __init__(self, age: int) -> None: # Requires pickable | ||
super().__init__(f"You're not old enough: {age}") | ||
``` | ||
|
||
## How it should be | ||
|
||
```py | ||
# Generic implementation: | ||
class GenericReduceException(Exception) | ||
def __init__(self, *args, **kwargs) -> None: | ||
self.args = tuple([*args, *kwargs.values()]) # Saves all args/kwargs | ||
super().__init__(*args) | ||
|
||
def __reduce__(self) -> str | tuple[Any, ...]: | ||
return (self.__class__, self.args) # Return them here | ||
|
||
# You can also be a bit more verbose: | ||
class ManyArgsWITHReduce(Exception): | ||
def __init__(self, val1: str, val2: str) -> None: | ||
self.val1, self.val2 = val1, val2 | ||
super().__init__(f"{val1} {val2}") | ||
|
||
def __reduce__(self) -> str | tuple[Any, ...]: | ||
return (ManyArgsWITHReduce, (self.val1, self.val2)) | ||
``` | ||
|
||
|
||
## When this is fine | ||
|
||
This is ok if you don't care about pickable exceptions 🤷 or either if you have an exception: | ||
|
||
- Without a custom `__init__` defined; or | ||
- With `__init__` that receives only one string argument |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
from functools import partial | ||
|
||
from tryceratops import analyzers | ||
from tryceratops.violations import codes | ||
|
||
from .analyzer_helpers import assert_violation, read_sample | ||
|
||
|
||
def test_non_pickable_error(): | ||
tree = read_sample("class_non_pickable") | ||
analyzer = analyzers.classdefs.NonPickableAnalyzer() | ||
|
||
assert_non_pickable = partial( | ||
assert_violation, codes.NON_PICKABLE_CLASS[0], codes.NON_PICKABLE_CLASS[1] | ||
) | ||
|
||
violations = analyzer.check(tree, "filename") | ||
|
||
assert len(violations) == 2 | ||
|
||
assert_non_pickable(24, 0, violations[0]) | ||
assert_non_pickable(29, 0, violations[1]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
""" | ||
Violation: | ||
Implement __reduce__ to enforce class is pickable. | ||
""" | ||
|
||
|
||
from typing import Any | ||
|
||
|
||
class RandomClass: | ||
"""This is not even an exception""" | ||
|
||
|
||
class RegularException(Exception): | ||
pass | ||
|
||
|
||
class AnotherOkException(Exception): | ||
def __init__(self, val1: str) -> None: | ||
super().__init__(val1) | ||
|
||
|
||
class ManyArgsMissingReduce(Exception): | ||
def __init__(self, val1: str, val2: str) -> None: # Requires pickable | ||
super().__init__(f"{val1} {val2}") | ||
|
||
|
||
class CustomMissingReduce(Exception): | ||
def __init__(self, age: int) -> None: # Requires pickable | ||
super().__init__(f"You're not old enough: {age}") | ||
|
||
|
||
class ManyArgsWITHReduce(Exception): | ||
def __init__(self, val1: str, val2: str) -> None: | ||
self.val1, self.val2 = val1, val2 | ||
super().__init__(f"{val1} {val2}") | ||
|
||
def __reduce__(self) -> str | tuple[Any, ...]: | ||
return (ManyArgsWITHReduce, (self.val1, self.val2)) | ||
|
||
|
||
class CustomWITHReduce(Exception): | ||
def __init__(self, age: int) -> None: | ||
self.age = age | ||
super().__init__(f"You're not old enough: {age}") | ||
|
||
def __reduce__(self) -> str | tuple[Any, ...]: | ||
return (CustomMissingReduce, (self.age,)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import ast | ||
import typing as t | ||
|
||
from tryceratops.violations import codes | ||
|
||
from .base import BaseAnalyzer, visit_error_handler | ||
|
||
|
||
class NonPickableAnalyzer(BaseAnalyzer): | ||
violation_code = codes.NON_PICKABLE_CLASS | ||
|
||
def _find_method(self, node: ast.ClassDef, name: str) -> t.Optional[ast.FunctionDef]: | ||
for method in node.body: | ||
if isinstance(method, ast.FunctionDef) and method.name == name: | ||
return method | ||
|
||
return None | ||
|
||
@visit_error_handler | ||
def visit_ClassDef(self, node: ast.ClassDef) -> t.Any: | ||
is_exc = any([base for base in node.bases if getattr(base, "id") == "Exception"]) | ||
if is_exc is False: | ||
return self.generic_visit(node) | ||
|
||
init_method = self._find_method(node, "__init__") | ||
if init_method is None: | ||
return self.generic_visit(node) | ||
|
||
reduce_method = self._find_method(node, "__reduce__") | ||
if reduce_method is not None: | ||
# Good enough to say this is not a violation | ||
return self.generic_visit(node) | ||
|
||
# First arg would be self | ||
has_more_than_one_arg = len(init_method.args.args) > 1 | ||
if has_more_than_one_arg is False: | ||
return self.generic_visit(node) | ||
|
||
_, second_arg, *remaining_args = init_method.args.args | ||
if ( | ||
len(remaining_args) > 0 | ||
or second_arg.annotation | ||
and getattr(second_arg.annotation, "id") != "str" | ||
): | ||
# Pickle would break for non string args or for more than 1 arg | ||
self._mark_violation(node) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,23 @@ | ||
import ast | ||
from typing import Collection, List, Tuple, TypedDict | ||
import typing as t | ||
import typing_extensions as te | ||
|
||
from tryceratops.filters import FileFilter | ||
|
||
ParsedFileType = Tuple[str, ast.AST, FileFilter] | ||
ParsedFilesType = Collection[ParsedFileType] | ||
ParsedFileType = t.Tuple[str, ast.AST, FileFilter] | ||
ParsedFilesType = t.Collection[ParsedFileType] | ||
|
||
|
||
class PyprojectConfig(TypedDict): | ||
class PyprojectConfig(t.TypedDict): | ||
""" | ||
Represents the expected pyproject config to be loaded | ||
exclude: a list of path patterns to be excluded e.g. [/tests, /fixtures] | ||
ignore: a list of violations to be completely ignored e.g. [TRY002, TRY300] | ||
experimental: whether to enable experimental analyzers | ||
""" | ||
|
||
exclude: List[str] | ||
ignore: List[str] | ||
experimental: bool | ||
autofix: bool | ||
exclude: te.NotRequired[t.List[str]] | ||
ignore: te.NotRequired[t.List[str]] | ||
experimental: te.NotRequired[bool] | ||
autofix: te.NotRequired[bool] | ||
check_pickable: te.NotRequired[bool] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters