Skip to content

Commit eee3ce4

Browse files
Simplify module path resolution in module_utils
Replace _is_subpath helper with Path.is_relative_to() (available since 3.9), removing the double relative_to() call.
1 parent ee3aeaa commit eee3ce4

1 file changed

Lines changed: 6 additions & 26 deletions

File tree

Lib/profiling/sampling/module_utils.py

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -66,44 +66,24 @@ def extract_module_name(filename, path_info):
6666
return (str(filename), 'other')
6767

6868
# Check if it's in stdlib
69-
if path_info['stdlib'] and _is_subpath(file_path, path_info['stdlib']):
70-
try:
71-
rel_path = file_path.relative_to(path_info['stdlib'])
72-
return (_path_to_module(rel_path), 'stdlib')
73-
except ValueError:
74-
pass
69+
if path_info['stdlib'] and file_path.is_relative_to(path_info['stdlib']):
70+
return (_path_to_module(file_path.relative_to(path_info['stdlib'])), 'stdlib')
7571

7672
# Check site-packages
7773
for site_pkg in path_info['site_packages']:
78-
if _is_subpath(file_path, site_pkg):
79-
try:
80-
rel_path = file_path.relative_to(site_pkg)
81-
return (_path_to_module(rel_path), 'site-packages')
82-
except ValueError:
83-
continue
74+
if file_path.is_relative_to(site_pkg):
75+
return (_path_to_module(file_path.relative_to(site_pkg)), 'site-packages')
8476

8577
# Check other sys.path entries (project files)
8678
if not str(file_path).startswith(('<', '[')): # Skip special files
8779
for path_entry in path_info['sys_path']:
88-
if _is_subpath(file_path, path_entry):
89-
try:
90-
rel_path = file_path.relative_to(path_entry)
91-
return (_path_to_module(rel_path), 'project')
92-
except ValueError:
93-
continue
80+
if file_path.is_relative_to(path_entry):
81+
return (_path_to_module(file_path.relative_to(path_entry)), 'project')
9482

9583
# Fallback: just use the filename
9684
return (_path_to_module(file_path), 'other')
9785

9886

99-
def _is_subpath(file_path, parent_path):
100-
try:
101-
file_path.relative_to(parent_path)
102-
return True
103-
except (ValueError, OSError):
104-
return False
105-
106-
10787
def _path_to_module(path):
10888
if isinstance(path, str):
10989
path = Path(path)

0 commit comments

Comments
 (0)