fix use of importlib.util.find_spec
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent c8cf469 · Browse files · 3 files·+39 added−81 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+39 added−81 removed
- other:+39 added−81 removed
Provenance
- Commit
bda295d- Tree
cd5ff16- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
c8cf469
3 files changed+39 added−81 removed
modified:src/flask/helpers.py+10 added-3 removed
573 unmodified lines574 if mod is not None and hasattr(mod, "__file__") and mod.__file__ is not None:575 return os.path.dirname(os.path.abspath(mod.__file__))576 577 # Next attempt: check the loader.578- spec = importlib.util.find_spec(import_name)579- loader = spec.loader if spec is not None else None578+ try:579+ spec = importlib.util.find_spec(import_name)580 581+ if spec is None:582+ raise ValueError583+ except (ImportError, ValueError):584+ loader = None585+ else:586+ loader = spec.loader587+588 # Loader does not exist or we're referring to an unloaded main589 # module or a main module without path (interactive sessions), go590 # with the current working directory.584- if loader is None or import_name == "__main__":591+ if loader is None:592 return os.getcwd()593 594 if hasattr(loader, "get_filename"):595 filepath = loader.get_filename(import_name)106 unmodified linesmodified:src/flask/scaffold.py+28 added-78 removed
777 unmodified lines778 assert view_func is not None, "expected view func if endpoint is not provided."779 return view_func.__name__780 781 782-def _matching_loader_thinks_module_is_package(loader, mod_name):783- """Attempt to figure out if the given name is a package or a module.784-785- :param: loader: The loader that handled the name.786- :param mod_name: The name of the package or module.787- """788- # Use loader.is_package if it's available.789- if hasattr(loader, "is_package"):790- return loader.is_package(mod_name)791-792- cls = type(loader)793-794- # NamespaceLoader doesn't implement is_package, but all names it795- # loads must be packages.796- if cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":797- return True798-799- # Otherwise we need to fail with an error that explains what went800- # wrong.801- raise AttributeError(802- f"'{cls.__name__}.is_package()' must be implemented for PEP 302"803- f" import hooks."804- )805-806-782 def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:783 # Path.is_relative_to doesn't exist until Python 3.9784 try:785 path.relative_to(base)10 unmodified lines796 root_spec = importlib.util.find_spec(root_mod_name)797 798 if root_spec is None:799 raise ValueError("not found")825- # ImportError: the machinery told us it does not exist826- # ValueError:827- # - the module name was invalid828- # - the module name is __main__829- # - *we* raised `ValueError` due to `root_spec` being `None`800 except (ImportError, ValueError):831- pass # handled below832- else:801+ # ImportError: the machinery told us it does not exist802+ # ValueError:803+ # - the module name was invalid804+ # - the module name is __main__805+ # - we raised `ValueError` due to `root_spec` being `None`806+ return os.getcwd()807+808+ if root_spec.origin in {"namespace", None}:809 # namespace package834- if root_spec.origin in {"namespace", None}:835- package_spec = importlib.util.find_spec(import_name)836- if package_spec is not None and package_spec.submodule_search_locations:837- # Pick the path in the namespace that contains the submodule.838- package_path = pathlib.Path(839- os.path.commonpath(package_spec.submodule_search_locations)840- )841- search_locations = (842- location843- for location in root_spec.submodule_search_locations844- if _path_is_relative_to(package_path, location)845- )846- else:847- # Pick the first path.848- search_locations = iter(root_spec.submodule_search_locations)849- return os.path.dirname(next(search_locations))850- # a package (with __init__.py)851- elif root_spec.submodule_search_locations:852- return os.path.dirname(os.path.dirname(root_spec.origin))853- # just a normal module810+ package_spec = importlib.util.find_spec(import_name)811+812+ if package_spec is not None and package_spec.submodule_search_locations:813+ # Pick the path in the namespace that contains the submodule.814+ package_path = pathlib.Path(815+ os.path.commonpath(package_spec.submodule_search_locations)816+ )817+ search_location = next(818+ location819+ for location in root_spec.submodule_search_locations820+ if _path_is_relative_to(package_path, location)821+ )822 else:855- return os.path.dirname(root_spec.origin)823+ # Pick the first path.824+ search_location = root_spec.submodule_search_locations[0]825 857- # we were unable to find the `package_path` using PEP 451 loaders858- spec = importlib.util.find_spec(root_mod_name)859- loader = spec.loader if spec is not None else None860-861- if loader is None or root_mod_name == "__main__":862- # import name is not found, or interactive/main module863- return os.getcwd()864-865- if hasattr(loader, "get_filename"):866- filename = loader.get_filename(root_mod_name)867- elif hasattr(loader, "archive"):868- # zipimporter's loader.archive points to the .zip file.869- filename = loader.archive826+ return os.path.dirname(search_location)827+ elif root_spec.submodule_search_locations:828+ # package with __init__.py829+ return os.path.dirname(os.path.dirname(root_spec.origin))830 else:871- # At least one loader is missing both get_filename and archive:872- # Google App Engine's HardenedModulesHook, use __file__.873- filename = importlib.import_module(root_mod_name).__file__831+ # module832+ return os.path.dirname(root_spec.origin)833 875- package_path = os.path.abspath(os.path.dirname(filename))834 877- # If the imported name is a package, filename is currently pointing878- # to the root of the package, need to get the current directory.879- if _matching_loader_thinks_module_is_package(loader, root_mod_name):880- package_path = os.path.dirname(package_path)881-882- return package_path883-884-835 def find_package(import_name: str):836 """Find the prefix that a package is installed under, and the path837 that it would be imported from.838 35 unmodified linesmodified:CHANGES.rst+1 added
3 unmodified lines4 Unreleased5 6 - Python 3.12 compatibility.7 - Update Werkzeug requirement to >=2.3.5.8+- Refactor how an app's root and instance paths are determined. :issue:`5160`9 10 11 Version 2.3.212 -------------1503 unmodified lines