From 9510f0b1c09f4869cd16dbaf40d39649c6915d93 Mon Sep 17 00:00:00 2001 From: enkore Date: Tue, 26 Feb 2013 00:56:09 +0100 Subject: [PATCH] Added ability to automatically import modules I thought: Well, isn't it a bit redundant if I go ahead and say in my config "import this-n-that and temp and load and alsa" while later just giving register() the modules. So register() (/ClassFinder as the backend) now support just naming a module as the first parameter. That module is then imported and searched for a class as usual. Just for reference the synopsis of Status.register(): register(mod.SomeChecker()) register(mod, setting1=..., setting2=...) register(mod, {"setting1:":, "setting2":...}) register("mod", setting=1..., setting2=...) register("mod", {"setting1:":, "setting2":...}) Fun fact: Actually register() doesn't care for it's arguments. They're passed straight into ClassFinder.instanciate_class_from_module (something I should definitely rename), which checks if it's first parameter is one of: -Python module => It calls ClassFinder.get_class with the same parameters => get_class will search the module using ClassFinder.search_module and return a matching class if and only if there is a single matching class in the module -string => It calls ClassFinder.get_module to import the module and calls itself on the result -something else => It returns that something The actual variation in passing the settings (keyword arguments vs. dict) is handled in SettingsBase. --- i3pystatus/core/util.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/i3pystatus/core/util.py b/i3pystatus/core/util.py index 179cf98..1c37eb9 100644 --- a/i3pystatus/core/util.py +++ b/i3pystatus/core/util.py @@ -149,9 +149,14 @@ class ClassFinder: return classes[0] + def get_module(self, module): + return getattr(__import__("i3pystatus.{module}".format(module=module), globals(), {}, []), module) + def instanciate_class_from_module(self, module, *args, **kwargs): if isinstance(module, types.ModuleType): return self.get_class(module)(*args, **kwargs) + elif isinstance(module, str): + return self.instanciate_class_from_module(self.get_module(module), *args, **kwargs) elif args or kwargs: raise ValueError("Additional arguments are invalid if 'module' is already an object") return module