Load an object given its absolute object path, and return it. The object can be the import path of a class, function, variable or an instance, e.g. 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware'. If ``path`` is not a string, but is a callable object, such as a class or
(path: str | Callable[..., Any])
| 56 | |
| 57 | |
| 58 | def load_object(path: str | Callable[..., Any]) -> Any: |
| 59 | """Load an object given its absolute object path, and return it. |
| 60 | |
| 61 | The object can be the import path of a class, function, variable or an |
| 62 | instance, e.g. 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware'. |
| 63 | |
| 64 | If ``path`` is not a string, but is a callable object, such as a class or |
| 65 | a function, then return it as is. |
| 66 | """ |
| 67 | |
| 68 | if not isinstance(path, str): |
| 69 | if callable(path): |
| 70 | return path |
| 71 | raise TypeError( |
| 72 | f"Unexpected argument type, expected string or object, got: {type(path)}" |
| 73 | ) |
| 74 | |
| 75 | try: |
| 76 | dot = path.rindex(".") |
| 77 | except ValueError: |
| 78 | raise ValueError(f"Error loading object '{path}': not a full path") from None |
| 79 | |
| 80 | module, name = path[:dot], path[dot + 1 :] |
| 81 | mod = import_module(module) |
| 82 | |
| 83 | try: |
| 84 | obj = getattr(mod, name) |
| 85 | except AttributeError: |
| 86 | raise NameError( |
| 87 | f"Module '{module}' doesn't define any object named '{name}'" |
| 88 | ) from None |
| 89 | |
| 90 | return obj |
| 91 | |
| 92 | |
| 93 | def walk_modules_iter(path: str) -> Iterable[ModuleType]: |
no outgoing calls
searching dependent graphs…