Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/python_path.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import inspect
6 import os
7
8
9 def find_object(path):
10 """
11 Find a Python object given a path of the form <modulepath>:<objectpath>.
12 Conceptually equivalent to
13
14 def find_object(modulepath, objectpath):
15 import <modulepath> as mod
16 return mod.<objectpath>
17 """
18 if path.count(":") != 1:
19 raise ValueError(f'python path {path!r} does not have the form "module:object"')
20
21 modulepath, objectpath = path.split(":")
22 obj = __import__(modulepath)
23 for a in modulepath.split(".")[1:]:
24 obj = getattr(obj, a)
25 for a in objectpath.split("."):
26 obj = getattr(obj, a)
27 return obj
28
29
30 def import_sibling_modules(exceptions=None):
31 """
32 Import all Python modules that are siblings of the calling module.
33
34 Args:
35 exceptions (list): A list of file names to exclude (caller and
36 __init__.py are implicitly excluded).
37 """
38 frame = inspect.stack()[1]
39 mod = inspect.getmodule(frame[0])
40
41 name = os.path.basename(mod.__file__) # type: ignore
42 excs = {"__init__.py", name}
43 if exceptions:
44 excs.update(exceptions)
45
46 modpath = mod.__name__ # type: ignore
47 if not name.startswith("__init__.py"):
48 modpath = modpath.rsplit(".", 1)[0]
49
50 for f in os.listdir(os.path.dirname(mod.__file__)): # type: ignore
51 if f.endswith(".py") and f not in excs:
52 __import__(modpath + "." + f[:-3])