[elbe-devel] [PATCH] elbepack: make use of importlib.import_module

Thomas Weißschuh thomas.weissschuh at linutronix.de
Wed Mar 20 08:45:21 CET 2024


Instead of manually messing with __import__ and sys.modules use
importlib which provides a nice interface for the module loader.

Signed-off-by: Thomas Weißschuh <thomas.weissschuh at linutronix.de>
---
 elbe                        | 11 ++---------
 elbepack/commands/daemon.py |  5 ++---
 elbepack/directories.py     |  2 +-
 3 files changed, 5 insertions(+), 13 deletions(-)

diff --git a/elbe b/elbe
index d688b5d105f2..9f4905743681 100755
--- a/elbe
+++ b/elbe
@@ -4,15 +4,9 @@
 # SPDX-License-Identifier: GPL-3.0-or-later
 # SPDX-FileCopyrightText: 2013-2017 Linutronix GmbH
 
+import importlib
 import sys
 
-# We need to import elbepack.commands so that
-# elbepack/commands/__init__.py is run and the commands package is
-# register into the elbepack namespace.  This is later use by
-# get_cmd_list() and the magic stuff with __import__() at the end of
-# this file
-#
-import elbepack.commands  # noqa: F401
 from elbepack.directories import get_cmdlist
 from elbepack.version import elbe_version
 
@@ -42,7 +36,6 @@ if sys.argv[1] not in cmd_list:
 
 modname = 'elbepack.commands.' + sys.argv[1]
 
-mod = __import__(modname)
-cmdmod = sys.modules[modname]
+cmdmod = importlib.import_module(modname)
 
 cmdmod.run_command(sys.argv[2:])
diff --git a/elbepack/commands/daemon.py b/elbepack/commands/daemon.py
index edcfbf168d77..04bc1a6c6987 100644
--- a/elbepack/commands/daemon.py
+++ b/elbepack/commands/daemon.py
@@ -2,7 +2,7 @@
 # SPDX-License-Identifier: GPL-3.0-or-later
 # SPDX-FileCopyrightText: 2014, 2017 Linutronix GmbH
 
-import sys
+import importlib
 from optparse import OptionParser
 from pkgutil import iter_modules
 
@@ -37,8 +37,7 @@ def run_command(argv):
     for d in daemons:
         print(f'enable {d}')
         module = 'elbepack.daemons.' + str(d)
-        _ = __import__(module)
-        cmdmod = sys.modules[module]
+        cmdmod = importlib.import_module(module)
         cherrypy.tree.graft(
             cmdmod.get_app(cherrypy.engine), '/' + str(d))
 
diff --git a/elbepack/directories.py b/elbepack/directories.py
index 2501ff6e21af..207c4d53b097 100644
--- a/elbepack/directories.py
+++ b/elbepack/directories.py
@@ -8,7 +8,7 @@ import subprocess
 import sys
 from pkgutil import iter_modules
 
-import elbepack
+import elbepack.commands
 
 
 # set global variables that are used in other modules via imports

---
base-commit: 0494866f13a20374514e056391138199803f0060
change-id: 20240319-importlib-118e75f390ff

Best regards,
-- 
Thomas Weißschuh <thomas.weissschuh at linutronix.de>



More information about the elbe-devel mailing list