Skip to content
Myr

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

3 files+39 added−81 removed

modified:src/flask/helpers.py+10 added-3 removed
573 unmodified lines
574 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__))576577 # 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)580581 if spec is None:582 raise ValueError583 except (ImportError, ValueError):584 loader = None585 else:586 loader = spec.loader587588 # 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()593594 if hasattr(loader, "get_filename"):595 filepath = loader.get_filename(import_name)
106 unmodified lines
modified:src/flask/scaffold.py+28 added-78 removed
777 unmodified lines
778 assert view_func is not None, "expected view func if endpoint is not provided."779 return view_func.__name__780781782def _matching_loader_thinks_module_is_package(loader, mod_name):783 """Attempt to figure out if the given name is a package or a module.784785 :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)791792 cls = type(loader)793794 # 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 True798799 # 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 )805806782def _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 lines
796 root_spec = importlib.util.find_spec(root_mod_name)797798 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()807808 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)811812 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]825857 # 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 None860861 if loader is None or root_mod_name == "__main__":862 # import name is not found, or interactive/main module863 return os.getcwd()864865 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)833875 package_path = os.path.abspath(os.path.dirname(filename))834877 # 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)881882 return package_path883884835def 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 lines
modified:CHANGES.rst+1 added
3 unmodified lines
4Unreleased56- 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`91011Version 2.3.212-------------
1503 unmodified lines