mirror of
ssh://git.janware.com/srv/git/janware/proj/jw-python
synced 2026-01-15 01:52:56 +01:00
stree.StringTree: Add .parent and .root
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
51f08d3dce
commit
18117e4590
1 changed files with 15 additions and 3 deletions
|
|
@ -34,11 +34,13 @@ def cleanup_string(s: str) -> str:
|
|||
|
||||
class StringTree: # export
|
||||
|
||||
def __init__(self, path: str, content: str) -> None:
|
||||
def __init__(self, path: str, content: str, parent: StringTree|None=None) -> None:
|
||||
slog(DEBUG, f'Constructing StringTree(path="{path}", content="{content}")')
|
||||
self.__parent = parent
|
||||
self.children: OrderedDict[str, StringTree] = OrderedDict()
|
||||
self.content: Optional[str] = None
|
||||
self.__set(path, content)
|
||||
|
||||
assert(hasattr(self, "content"))
|
||||
#assert self.content is not None
|
||||
|
||||
|
|
@ -100,13 +102,13 @@ class StringTree: # export
|
|||
nibble = components[0]
|
||||
rest = '.'.join(components[1:])
|
||||
if nibble not in self.children:
|
||||
self.children[nibble] = StringTree('', content=nibble)
|
||||
self.children[nibble] = StringTree('', content=nibble, parent=self)
|
||||
if l > 1:
|
||||
assert len(rest) > 0
|
||||
return self.children[nibble].__set(rest, content=content)
|
||||
# last component, a.k.a. leaf
|
||||
if content is not None:
|
||||
gc = content if isinstance(content, StringTree) else StringTree('', content=content)
|
||||
gc = content if isinstance(content, StringTree) else StringTree('', content=content, parent=self.children[nibble])
|
||||
# Make sure no existing grand child is updated. It would reside too
|
||||
# far up in the grand child OrderedDict, we need it last
|
||||
if gc.content in self.children[nibble].children:
|
||||
|
|
@ -189,6 +191,16 @@ class StringTree: # export
|
|||
slog(DEBUG, f'Returning value from children {self.children}')
|
||||
return self.children[next(reversed(self.children))].content # type: ignore
|
||||
|
||||
@property
|
||||
def parent(self):
|
||||
return self.__parent
|
||||
|
||||
@property
|
||||
def root(self):
|
||||
if self.__parent is None:
|
||||
return self
|
||||
return self.__parent.root
|
||||
|
||||
def child_list(self, depth_first: bool=True) -> List[StringTree]:
|
||||
if depth_first == False:
|
||||
raise Exception("tried to retrieve child list with breadth-first search, not yet implemented")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue