Skip to content

Commit

Permalink
Don't import Hypothesis unless needed
Browse files Browse the repository at this point in the history
Fixes #26.
  • Loading branch information
Zac-HD committed Jan 17, 2022
1 parent 49f0813 commit 2501f9d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,7 @@

#### 0.8.0 - 2022-01-16
- Updated minimum dependency versions - bugfixes and improved support for Python 3.9+
- Avoid importing Hypothesis if it's not going to be used (#26)

#### 0.7.0 - 2021-12-23
- Python 3.6 is end-of-life, so format code as 3.7+
Expand Down
31 changes: 20 additions & 11 deletions src/shed/_codemods.py
Expand Up @@ -5,6 +5,7 @@
nitpicks about typing unions and literals.
"""

import re
from ast import literal_eval
from typing import Tuple

Expand All @@ -13,15 +14,22 @@
from libcst._parser.types.config import _pick_compatible_python_version
from libcst.codemod import VisitorBasedCodemodCommand

try:
from hypothesis.extra.codemods import (
HypothesisFixComplexMinMagnitude as Hy1,
HypothesisFixPositionalKeywonlyArgs as Hy2,
)
except ImportError: # pragma: no cover
hypothesis_fixers = []
else:
hypothesis_fixers = [Hy1, Hy2]

def attempt_hypothesis_codemods(context, mod): # pragma: no cover
try:
from hypothesis.extra.codemods import (
HypothesisFixComplexMinMagnitude,
HypothesisFixPositionalKeywonlyArgs,
)
except ImportError:
return mod
mod = HypothesisFixComplexMinMagnitude(context).transform_module(mod)
return HypothesisFixPositionalKeywonlyArgs(context).transform_module(mod)


imports_hypothesis = re.compile(
r"^ *(?:import hypothesis|from hypothesis(?:\.[a-z]+)* import )"
).search


def _run_codemods(code: str, min_version: Tuple[int, int]) -> str:
Expand All @@ -35,8 +43,9 @@ def _run_codemods(code: str, min_version: Tuple[int, int]) -> str:
config = cst.PartialParserConfig(python_version=f"{v.major}.{v.minor}")
mod = cst.parse_module(code, config)

for fixer in [ShedFixers] + hypothesis_fixers:
mod = fixer(context).transform_module(mod)
if imports_hypothesis(code): # pragma: no cover
mod = attempt_hypothesis_codemods(context, mod)
mod = ShedFixers(context).transform_module(mod)
return mod.code


Expand Down

0 comments on commit 2501f9d

Please sign in to comment.