1#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18from __future__ import annotations
19
20import pkgutil
21from collections.abc import Callable
22from importlib import import_module
23from typing import TYPE_CHECKING
24
25if TYPE_CHECKING:
26 from types import ModuleType
27
28
29def import_string(dotted_path: str):
30 """
31 Import a dotted module path and return the attribute/class designated by the last name in the path.
32
33 Raise ImportError if the import failed.
34 """
35 # TODO: Add support for nested classes. Currently, it only works for top-level classes.
36 try:
37 module_path, class_name = dotted_path.rsplit(".", 1)
38 except ValueError:
39 raise ImportError(f"{dotted_path} doesn't look like a module path")
40
41 module = import_module(module_path)
42
43 try:
44 return getattr(module, class_name)
45 except AttributeError:
46 raise ImportError(f'Module "{module_path}" does not define a "{class_name}" attribute/class')
47
48
49def qualname(o: object | Callable) -> str:
50 """Convert an attribute/class/function to a string importable by ``import_string``."""
51 if callable(o) and hasattr(o, "__module__") and hasattr(o, "__name__"):
52 return f"{o.__module__}.{o.__name__}"
53
54 cls = o
55
56 if not isinstance(cls, type): # instance or class
57 cls = type(cls)
58
59 name = cls.__qualname__
60 module = cls.__module__
61
62 if module and module != "__builtin__":
63 return f"{module}.{name}"
64
65 return name
66
67
68def iter_namespace(ns: ModuleType):
69 return pkgutil.iter_modules(ns.__path__, ns.__name__ + ".")
70
71
72def is_valid_dotpath(path: str) -> bool:
73 """
74 Check if a string follows valid dotpath format (ie: 'package.subpackage.module').
75
76 :param path: String to check
77 """
78 import re
79
80 if not isinstance(path, str):
81 return False
82
83 # Pattern explanation:
84 # ^ - Start of string
85 # [a-zA-Z_] - Must start with letter or underscore
86 # [a-zA-Z0-9_] - Following chars can be letters, numbers, or underscores
87 # (\.[a-zA-Z_][a-zA-Z0-9_]*)* - Can be followed by dots and valid identifiers
88 # $ - End of string
89 pattern = r"^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$"
90
91 return bool(re.match(pattern, path))