Skip to content

Commit db23a27

Browse files
committed
Only load .py with nodes
1 parent 90eca1e commit db23a27

File tree

1 file changed

+41
-10
lines changed

1 file changed

+41
-10
lines changed

example_nodes/__init__.py

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,58 @@
11
#!/usr/bin/python
22
import os
33
import sys
4-
import inspect
5-
import importlib
4+
import ast
5+
6+
7+
VALID_NODE_TYPE = ['BaseNode', 'AutoNode']
8+
9+
10+
def detectNodesFromText(filepath):
11+
"""returns Node names from a python script"""
12+
froms = []
13+
14+
with open(filepath, "r") as source:
15+
tree = ast.parse(source.read())
16+
17+
for node in tree.body:
18+
if isinstance(node, ast.ClassDef):
19+
for base in node.bases:
20+
if base.id in VALID_NODE_TYPE:
21+
for indef in node.body:
22+
if isinstance(indef, ast.Assign):
23+
for target in indef.targets:
24+
if target.id == '__identifier__':
25+
froms.append(node.name)
26+
return froms
627

728

829
def getNodesRecursively(path=__file__):
30+
""" Returns imported nodes. """
931
Nodes = []
1032
basedir, filename = os.path.split(path)
33+
rootModule = os.path.basename(basedir)
34+
1135
for root, dirs, files in os.walk(basedir, topdown=False):
1236
if root not in sys.path:
1337
sys.path.append(root)
1438

1539
for name in files:
1640
if name.endswith('.py') and not name.startswith('_'):
17-
module_name = name[:-3]
18-
module = importlib.import_module(module_name)
19-
for name, obj in inspect.getmembers(module):
20-
if inspect.isclass(obj) and not obj.__name__ == 'BaseNode':
21-
for clsObj in inspect.getmro(obj):
22-
if clsObj.__name__ == 'BaseNode':
23-
Nodes.append(obj)
24-
break
41+
module_name = root.split(rootModule)[1].replace('\\', '.') + name[:-3]
42+
modulePath = os.path.join(root, name)
43+
froms = detectNodesFromText(modulePath)
44+
if not froms:
45+
continue
46+
47+
try:
48+
mod = __import__(module_name, globals(), locals(), froms, 0)
49+
for node in froms:
50+
Nodes.append(getattr(mod, node))
51+
52+
except ImportError as e:
53+
print ('Error in importing class: %s' % (e))
54+
continue
55+
2556
return Nodes
2657

2758

0 commit comments

Comments
 (0)