Check if the current Python environment contains all the libraries that are imported in a file.
(filename)
| 123 | |
| 124 | |
| 125 | def check_imports(filename): |
| 126 | """ |
| 127 | Check if the current Python environment contains all the libraries that are imported in a file. |
| 128 | """ |
| 129 | with open(filename, "r", encoding="utf-8") as f: |
| 130 | content = f.read() |
| 131 | |
| 132 | # Imports of the form `import xxx` |
| 133 | imports = re.findall(r"^\s*import\s+(\S+)\s*$", content, flags=re.MULTILINE) |
| 134 | # Imports of the form `from xxx import yyy` |
| 135 | imports += re.findall(r"^\s*from\s+(\S+)\s+import", content, flags=re.MULTILINE) |
| 136 | # Only keep the top-level module |
| 137 | imports = [imp.split(".")[0] for imp in imports if not imp.startswith(".")] |
| 138 | |
| 139 | # Unique-ify and test we got them all |
| 140 | imports = list(set(imports)) |
| 141 | missing_packages = [] |
| 142 | for imp in imports: |
| 143 | try: |
| 144 | importlib.import_module(imp) |
| 145 | except ImportError: |
| 146 | missing_packages.append(imp) |
| 147 | |
| 148 | if len(missing_packages) > 0: |
| 149 | raise ImportError( |
| 150 | "This modeling file requires the following packages that were not found in your environment: " |
| 151 | f"{', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`" |
| 152 | ) |
| 153 | |
| 154 | return get_relative_imports(filename) |
| 155 | |
| 156 | |
| 157 | def get_class_in_module(class_name, module_path): |
no test coverage detected