PageRenderTime 17ms CodeModel.GetById 2ms app.highlight 10ms RepoModel.GetById 2ms app.codeStats 0ms

/circuits/core/utils.py

https://bitbucket.org/prologic/circuits/
Python | 67 lines | 42 code | 18 blank | 7 comment | 22 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
 5"""Utils
 6
 7This module defines utilities used by circuits.
 8"""
 9
10import sys
11
12from imp import reload
13
14
15def flatten(root, visited=None):
16    if not visited:
17        visited = set()
18    yield root
19    for component in root.components.copy():
20        if component not in visited:
21            visited.add(component)
22            for child in flatten(component, visited):
23                yield child
24
25
26def findchannel(root, channel, all=False):
27    components = [x for x in flatten(root)
28                  if x.channel == channel]
29
30    if all:
31        return components
32
33    if components:
34        return components[0]
35
36
37def findtype(root, component, all=False):
38    components = [x for x in flatten(root)
39                  if issubclass(type(x), component)]
40
41    if all:
42        return components
43
44    if components:
45        return components[0]
46
47findcmp = findtype
48
49
50def findroot(component):
51    if component.parent == component:
52        return component
53    else:
54        return findroot(component.parent)
55
56
57def safeimport(name):
58    modules = sys.modules.copy()
59    try:
60        if name in sys.modules:
61            return reload(sys.modules[name])
62        else:
63            return __import__(name, globals(), locals(), [""])
64    except:
65        for name in sys.modules.copy():
66            if not name in modules:
67                del sys.modules[name]