Advertisement
Uno-Dan

A jog around the park!

Mar 18th, 2019
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1.     def element(self, uri, idx=None):
  2.         _path = uri.split('/')
  3.         if not _path:
  4.             return None
  5.  
  6.         def get_indexes(_idx):
  7.             indexes = []
  8.             if _idx is None:
  9.                 indexes = [0]
  10.             elif isinstance(_idx, int):
  11.                 indexes = [_idx]
  12.             elif isinstance(_idx, tuple):
  13.                 indexes = list(_idx)
  14.             elif isinstance(_idx, list):
  15.                 indexes = _idx
  16.  
  17.             cnt = len(_path)
  18.             if cnt > len(indexes):
  19.                 for i in range(0, cnt-1):
  20.                     indexes.insert(0, 0)
  21.             return indexes
  22.  
  23.         def get_element(parent, elm_type, elm_id):
  24.             def walk(_parent):
  25.                 for node in _parent.nodes.values():
  26.                     if node.type == elm_type and node.id == elm_id:
  27.                         return node
  28.                     if node.has_children:
  29.                         node = walk(node)
  30.                         if node:
  31.                             return node
  32.                 return None
  33.             return walk(parent)
  34.  
  35.         idxs = get_indexes(idx)
  36.         _type = _path.pop(0)
  37.         _id = f'{_type.lower()}{idxs.pop(0)}'
  38.  
  39.         elm = get_element(self, _type, _id)
  40.         if elm.uri == uri:
  41.             return elm
  42.  
  43.         while idxs:
  44.             _type = _path.pop(0)
  45.             _id = f'{_type.lower()}{idxs.pop(0)}'
  46.             elm = get_element(elm, _type, _id)
  47.         return elm
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement