Skip to content

Commit cf92ea0

Browse files
committed
improve ast constant extraction performance
1 parent cd800d4 commit cf92ea0

File tree

2 files changed

+19
-11
lines changed

2 files changed

+19
-11
lines changed

hypothesis-python/src/hypothesis/internal/constants_ast.py

+15-7
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
if TYPE_CHECKING:
2424
from typing import TypeAlias
2525

26-
ConstantT: "TypeAlias" = Union[int, float, bool, bytes, str]
26+
ConstantT: "TypeAlias" = Union[int, float, bytes, str]
2727

2828

2929
class ConstantVisitor(NodeVisitor):
@@ -103,12 +103,20 @@ def _module_ast(module: ModuleType) -> Optional[AST]:
103103
def local_modules() -> tuple[ModuleType, ...]:
104104
modules = []
105105
for module in sys.modules.values():
106-
if not hasattr(module, "__file__"):
107-
continue
108-
if module.__file__ is None: # pragma: no cover
109-
continue
110-
111-
if ModuleLocation.from_path(module.__file__) is not ModuleLocation.LOCAL:
106+
if (
107+
not hasattr(module, "__file__")
108+
or module.__file__ is None
109+
# Skip expensive path lookup for stdlib modules.
110+
# This will cause false negatives if a user names their module the
111+
# same as a stdlib module.
112+
#
113+
# sys.stdlib_module_names is new in 3.10
114+
or (
115+
sys.version_info >= (3, 10)
116+
and module.__name__ in sys.stdlib_module_names
117+
)
118+
or ModuleLocation.from_path(module.__file__) is not ModuleLocation.LOCAL
119+
):
112120
continue
113121

114122
modules.append(module)

hypothesis-python/src/hypothesis/internal/scrutineer.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -217,14 +217,14 @@ def get_explaining_locations(traces):
217217

218218
# see e.g. https://docs.python.org/3/library/sysconfig.html#posix-user
219219
# for examples of these path schemes
220-
STDLIB_DIRS = [
220+
STDLIB_DIRS = {
221221
Path(sysconfig.get_path("platstdlib")).resolve(),
222222
Path(sysconfig.get_path("stdlib")).resolve(),
223-
]
224-
SITE_PACKAGES_DIRS = [
223+
}
224+
SITE_PACKAGES_DIRS = {
225225
Path(sysconfig.get_path("purelib")).resolve(),
226226
Path(sysconfig.get_path("platlib")).resolve(),
227-
]
227+
}
228228

229229
EXPLANATION_STUB = (
230230
"Explanation:",

0 commit comments

Comments
 (0)