/circuits/core/utils.py

https://bitbucket.org/prologic/circuits/ · Python · 67 lines · 42 code · 18 blank · 7 comment · 19 complexity · ba5b44a9b4624b5c378e23fdb8850048 MD5 · raw file

  1. # Module: utils
  2. # Date: 11th April 2010
  3. # Author: James Mills, prologic at shortcircuit dot net dot au
  4. """Utils
  5. This module defines utilities used by circuits.
  6. """
  7. import sys
  8. from imp import reload
  9. def flatten(root, visited=None):
  10. if not visited:
  11. visited = set()
  12. yield root
  13. for component in root.components.copy():
  14. if component not in visited:
  15. visited.add(component)
  16. for child in flatten(component, visited):
  17. yield child
  18. def findchannel(root, channel, all=False):
  19. components = [x for x in flatten(root)
  20. if x.channel == channel]
  21. if all:
  22. return components
  23. if components:
  24. return components[0]
  25. def findtype(root, component, all=False):
  26. components = [x for x in flatten(root)
  27. if issubclass(type(x), component)]
  28. if all:
  29. return components
  30. if components:
  31. return components[0]
  32. findcmp = findtype
  33. def findroot(component):
  34. if component.parent == component:
  35. return component
  36. else:
  37. return findroot(component.parent)
  38. def safeimport(name):
  39. modules = sys.modules.copy()
  40. try:
  41. if name in sys.modules:
  42. return reload(sys.modules[name])
  43. else:
  44. return __import__(name, globals(), locals(), [""])
  45. except:
  46. for name in sys.modules.copy():
  47. if not name in modules:
  48. del sys.modules[name]