Debian Codegraph @

gi/importer.py

raw
1 # Copyright (C) 2005-2009 Johan Dahlin <[email protected]>
2 # 2015 Christoph Reiter
3 #
4 # importer.py: dynamic importer for introspected libraries.
5 #
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License, or (at your option) any later version.
10 #
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 # USA
20
21 import sys
22 import warnings
23 import importlib
24 from contextlib import contextmanager
25
26 import gi
27 from ._gi import Repository, RepositoryError
28 from ._gi import PyGIWarning
29 from .module import get_introspection_module
30 from .overrides import load_overrides
31
32
33 repository = Repository.get_default()
34
35 # only for backwards compatibility
36 modules = {}
37
38
39 @contextmanager
40 def _check_require_version(namespace, stacklevel):
41 """A context manager which tries to give helpful warnings
42 about missing gi.require_version() which could potentially
43 break code if only an older version than expected is installed
44 or a new version gets introduced.
45
46 ::
47
48 with _check_require_version("Gtk", stacklevel):
49 load_namespace_and_overrides()
50 """
51 was_loaded = repository.is_registered(namespace)
52
53 yield
54
55 if was_loaded:
56 # it was loaded before by another import which depended on this
57 # namespace or by C code like libpeas
58 return
59
60 if namespace in ("GLib", "GObject", "Gio", "GioUnix", "GioWin32"):
61 # part of glib (we have bigger problems if versions change there)
62 return
63
64 if gi.get_required_version(namespace) is not None:
65 # the version was forced using require_version()
66 return
67
68 version = repository.get_version(namespace)
69 warnings.warn(
70 f"{namespace} was imported without specifying a version first. "
71 f"Use gi.require_version('{namespace}', '{version}') before "
72 "import to ensure that the right version gets loaded.",
73 PyGIWarning,
74 stacklevel=stacklevel,
75 )
76
77
78 def get_import_stacklevel(import_hook):
79 """Returns the stacklevel value for warnings.warn() for when the warning
80 gets emitted by an imported module, but the warning should point at the
81 code doing the import.
82
83 Pass import_hook=True if the warning gets generated by an import hook
84 (warn() gets called in load_module(), see PEP302)
85 """
86 py_version = sys.version_info[:2]
87 if py_version <= (3, 2):
88 # 2.7 included
89 return 4 if import_hook else 2
90 if py_version == (3, 3):
91 return 8 if import_hook else 10
92 if py_version == (3, 4):
93 return 10 if import_hook else 8
94 # fixed again in 3.5+, see https://bugs.python.org/issue24305
95 return 4 if import_hook else 2
96
97
98 class DynamicImporter:
99 # Note: see PEP302 for the Importer Protocol implemented below.
100
101 def __init__(self, path):
102 self.path = path
103
104 def _find_module_check(self, fullname):
105 if not fullname.startswith(self.path):
106 return False
107
108 path, _namespace = fullname.rsplit(".", 1)
109 return path == self.path
110
111 def find_spec(self, fullname, path=None, target=None):
112 if self._find_module_check(fullname):
113 return importlib.util.spec_from_loader(fullname, self)
114 return None
115
116 def find_module(self, fullname, path=None):
117 if self._find_module_check(fullname):
118 return self
119 return None
120
121 def create_module(self, spec):
122 _path, namespace = spec.name.rsplit(".", 1)
123
124 # is_registered() is faster than enumerate_versions() and
125 # in the common case of a namespace getting loaded before its
126 # dependencies, is_registered() returns True for all dependencies.
127 if not repository.is_registered(
128 namespace
129 ) and not repository.enumerate_versions(namespace):
130 raise ImportError(
131 f"cannot import name {namespace}, introspection typelib not found"
132 )
133
134 stacklevel = get_import_stacklevel(import_hook=True)
135 with _check_require_version(namespace, stacklevel=stacklevel):
136 try:
137 introspection_module = get_introspection_module(namespace)
138 except RepositoryError as e:
139 raise ImportError(e) from e
140 # Import all dependencies first so their init functions
141 # (gdk_init, ..) in overrides get called.
142 # https://bugzilla.gnome.org/show_bug.cgi?id=656314
143 for dep in repository.get_immediate_dependencies(namespace):
144 importlib.import_module("gi.repository." + dep.split("-")[0])
145 return load_overrides(introspection_module)
146
147 def exec_module(self, fullname):
148 # “exec” the module and consequently populate the module's namespace
149 pass