From 9348e883ad7eda50632aa4af8569ea22f4cf2813 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 22 Oct 2024 12:35:32 -1000 Subject: [PATCH] Improve performance of calculate_relative_path (#1382) --- CHANGES/1382.feature.rst | 1 + yarl/_path.py | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) create mode 120000 CHANGES/1382.feature.rst diff --git a/CHANGES/1382.feature.rst b/CHANGES/1382.feature.rst new file mode 120000 index 000000000..62a3dbc9b --- /dev/null +++ b/CHANGES/1382.feature.rst @@ -0,0 +1 @@ +1340.feature.rst \ No newline at end of file diff --git a/yarl/_path.py b/yarl/_path.py index f7995ddc5..838aa94cb 100644 --- a/yarl/_path.py +++ b/yarl/_path.py @@ -2,6 +2,7 @@ from collections.abc import Sequence from contextlib import suppress +from itertools import chain from pathlib import PurePosixPath @@ -54,11 +55,11 @@ def calculate_relative_path(target: str, base: str) -> str: target_path = PurePosixPath(target) base_path = PurePosixPath(base) - if not base[-1] == "/": + if base[-1] != "/": base_path = base_path.parent - for step, path in enumerate((base_path, *base_path.parents)): - if target_path.is_relative_to(path): + for step, path in enumerate(chain((base_path,), base_path.parents)): + if path == target_path or path in target_path.parents: break elif path.name == "..": raise ValueError(f"'..' segment in {str(base_path)!r} cannot be walked")