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.
This commit is contained in:
enkore 2013-02-26 00:56:09 +01:00
parent b404b85cbb
commit 9510f0b1c0

View File

@ -149,9 +149,14 @@ class ClassFinder:
return classes[0] 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): def instanciate_class_from_module(self, module, *args, **kwargs):
if isinstance(module, types.ModuleType): if isinstance(module, types.ModuleType):
return self.get_class(module)(*args, **kwargs) 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: elif args or kwargs:
raise ValueError("Additional arguments are invalid if 'module' is already an object") raise ValueError("Additional arguments are invalid if 'module' is already an object")
return module return module