Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].__spec__ is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modules, then sys.meta_pat
(name, package=None)
| 67 | |
| 68 | |
| 69 | def find_spec(name, package=None): |
| 70 | """Return the spec for the specified module. |
| 71 | |
| 72 | First, sys.modules is checked to see if the module was already imported. If |
| 73 | so, then sys.modules[name].__spec__ is returned. If that happens to be |
| 74 | set to None, then ValueError is raised. If the module is not in |
| 75 | sys.modules, then sys.meta_path is searched for a suitable spec with the |
| 76 | value of 'path' given to the finders. None is returned if no spec could |
| 77 | be found. |
| 78 | |
| 79 | If the name is for submodule (contains a dot), the parent module is |
| 80 | automatically imported. |
| 81 | |
| 82 | The name and package arguments work the same as importlib.import_module(). |
| 83 | In other words, relative module names (with leading dots) work. |
| 84 | |
| 85 | """ |
| 86 | fullname = resolve_name(name, package) if name.startswith('.') else name |
| 87 | if fullname not in sys.modules: |
| 88 | parent_name = fullname.rpartition('.')[0] |
| 89 | if parent_name: |
| 90 | parent = __import__(parent_name, fromlist=['__path__']) |
| 91 | try: |
| 92 | parent_path = parent.__path__ |
| 93 | except AttributeError as e: |
| 94 | raise ModuleNotFoundError( |
| 95 | f"__path__ attribute not found on {parent_name!r} " |
| 96 | f"while trying to find {fullname!r}", name=fullname) from e |
| 97 | else: |
| 98 | parent_path = None |
| 99 | return _find_spec(fullname, parent_path) |
| 100 | else: |
| 101 | module = sys.modules[fullname] |
| 102 | if module is None: |
| 103 | return None |
| 104 | try: |
| 105 | spec = module.__spec__ |
| 106 | except AttributeError: |
| 107 | raise ValueError(f'{name}.__spec__ is not set') from None |
| 108 | else: |
| 109 | if spec is None: |
| 110 | raise ValueError(f'{name}.__spec__ is None') |
| 111 | return spec |
| 112 | |
| 113 | |
| 114 | # Normally we would use contextlib.contextmanager. However, this module |
no test coverage detected
searching dependent graphs…