Debian Codegraph @

docs/guide/imports.rst

raw
1 Imports
2 =======
3
4 The toplevel ``gi`` package allows you to import the different libraries
5 namespaces and ensure specific versions of them.
6
7 The next code line will import the ``GTK`` and ``GLib`` libraries from the
8 ``gi.repository`` module. ``gi.repository`` holds the libraries bindings.
9
10 .. code:: python
11
12 from gi.repository import Gtk, GLib
13
14
15 If you want to ensure a specific version of a library you can use :func:`gi.require_version`.
16
17 .. code:: python
18
19 import gi
20 gi.require_version('Gtk', '4.0')
21 gi.require_version('GLib', '2.0')
22 from gi.repository import Gtk, GLib
23
24
25 Currently, when importing ``Gdk`` or ``Gtk``, their init functions
26 (``Gdk.init_check()`` and ``Gtk.init_check()`` respectively) will be
27 automatically called for backwards-compatibility reasons.
28 This prevents, among other things, to use ``Gtk.disable_setlocale()``, as
29 it shall be called before ``Gtk`` initialization.
30
31 This behavior may be dropped in the future, but in the meanwhile you can
32 use :func:`gi.disable_legacy_autoinit` before the import to skip the
33 auto-init.
34
35 .. code:: python
36
37 import gi
38 gi.disable_legacy_autoinit()
39 from gi.repository import Gtk
40
41
42 To avoid `PEP8/E402 <https://www.flake8rules.com/rules/E402.html>`_ you can
43 use a try block.
44
45 .. code:: python
46
47 import sys
48
49 import gi
50 try:
51 gi.require_version('Gtk', '4.0')
52 gi.require_version('Adw', '1')
53 from gi.repository import Adw, Gtk
54 except ImportError or ValueError as exc:
55 print('Error: Dependencies not met.', exc)
56 sys.exit(1)
57
58
59 .. seealso::
60 For more detailed information of the methods provided by the ``gi`` module
61 checkout :ref:`guide-api`.