PageRenderTime 34ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/ironfroggy-straight.plugin-57ef11c/ironfroggy-straight.plugin-57ef11c/README

#
#! | 71 lines | 48 code | 23 blank | 0 comment | 0 complexity | bc7fa6453d78ed8534e2105ee14e1874 MD5 | raw file
  1. # straight.plugin
  2. straight.plugin is a Python plugin loader inspired by twisted.plugin with two
  3. important distinctions:
  4. - Fewer dependencies
  5. - Python 3 compatible
  6. The system is used to allow multiple Python packages to provide plugins within
  7. a namespace package, where other packages will locate and utilize. The plugins
  8. themselves are modules in a namespace package where the namespace identifies
  9. the plugins in it for some particular purpose or intent.
  10. For example, if I was building a log parser, I might tell users that he parser
  11. will look for plugins in the `logfilter` namespace. Someone else could then
  12. provide a module named `logfilter.normalizedates` and my parser would find this
  13. plugin, load it, and use it to filter the log entries.
  14. It would be up to me to document what the plugin actually looks like, based on
  15. how I need to use it in my project.
  16. ## Using plugins
  17. from straight.plugin import load
  18. class Skip(Exception):
  19. pass
  20. plugins = load('logfilter')
  21. def filter_entry(log_entry):
  22. for plugin in plugins:
  23. try:
  24. log_entry = plugin.filter(log_entry)
  25. except Skip:
  26. pass
  27. return log_entry
  28. ## Writing plugins
  29. # logfilter/__init__.py
  30. from pkgutil import extend_path
  31. __path__ = extend_path(__path__, __name__)
  32. # logfilter/hide_extra.py
  33. from logfilter import Skip
  34. def filter(log_entry):
  35. level = log_entry.split(':', 1)[0]
  36. if level != 'EXTRA':
  37. return log_entry
  38. else:
  39. raise Skip()
  40. ## Module and Class Plugins
  41. straight.plugin is able to load both modules and classes, depending on your
  42. needs. When you call `load()` with a namespace, you'll get all the modules
  43. found under that namespace. When you call it with the optional `subclasses`
  44. parameter, all the classes which are subclases of the given type will be
  45. given.
  46. # Example
  47. from straight.plugins import load
  48. plugins = load("ircclient", subclasses=IrcClientCommand)