Skip to content

Commit

Permalink
Merge pull request #28 from leonardbinet/mypy
Browse files Browse the repository at this point in the history
v1.2.0
  • Loading branch information
leonardbinet authored Jul 26, 2021
2 parents 200a6cf + 3004019 commit fed7c54
Show file tree
Hide file tree
Showing 9 changed files with 175 additions and 204 deletions.
50 changes: 31 additions & 19 deletions lighttree/implementations/json_tree.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from typing import Dict, Optional, Any, Union, List
from lighttree import Node, Tree, Key
from lighttree.node import NodeId
from lighttree.interactive import TreeBasedObj


class JsonTree(Tree):
def __init__(
self, d: Dict = None, strict: bool = True, path_separator: str = "."
self, d: Optional[Dict] = None, strict: bool = True, path_separator: str = "."
) -> None:
"""
:param d:
Expand All @@ -23,53 +25,63 @@ def _concat(a: Any, b: Any) -> str:
return str(b)
return ".".join([str(a), str(b)])

def _fill(
self, data: Any, key: Key, strict: bool, path: Optional[str] = None
) -> None:
def _fill(self, data: Any, key: Key, strict: bool, path: str = "") -> None:
pid: Optional[NodeId]
if self.is_empty():
pid = None
else:
pid = self.get_node_id_by_path(path=path)
if isinstance(data, list) or not strict and isinstance(data, tuple):
k = self.insert_node(
Node(keyed=False), parent_id=path, key=key, by_path=True
)
k = self.insert_node(Node(keyed=False), parent_id=pid, key=key)
path = self._concat(path, k)
for el in data:
self._fill(el, strict=strict, path=path, key=None)
return
if isinstance(data, dict):
k = self.insert_node(
Node(keyed=True), key=key, parent_id=path, by_path=True
)
k = self.insert_node(Node(keyed=True), key=key, parent_id=pid)
path = self._concat(path, k)
for sk, el in data.items():
self._fill(el, strict=strict, path=path, key=sk)
return
if isinstance(data, (str, int, float)):
self.insert_node(
Node(accept_children=False, repr_=data, data=data),
parent_id=path,
Node(accept_children=False, repr_=str(data), data=data),
parent_id=pid,
key=key,
by_path=True,
)
return
if data is None:
self.insert_node(Node(accept_children=False), parent_id=path, by_path=True)
self.insert_node(Node(accept_children=False), parent_id=pid)
return
raise TypeError("Unsupported type %s" % type(data))

def to_dict(self) -> Union[Dict, List, None]:
def to_json(self) -> Union[Dict, List, None]:
if self.root is None:
return None
return self._to_dict(self.root)
return self._to_json(self.root)

def _to_dict(self, nid: str) -> Any:
def _to_json(self, nid: NodeId) -> Any:
_, n = self.get(nid)
if not n.accept_children:
return n.data
if n.keyed:
d = {}
for sk, sn in self.children(n.identifier):
d[sk] = self._to_dict(sn.identifier)
d[sk] = self._to_json(sn.identifier)
return d
l_ = []
for _, sn in self.children(n.identifier):
l_.append(self._to_dict(sn.identifier))
l_.append(self._to_json(sn.identifier))
return l_


class InteractiveJson(TreeBasedObj):

_tree: JsonTree

def __call__(self, *args: Any, **kwargs: Any) -> Any:
return self._tree.to_json()


def as_interactive_json(d: Any, strict: bool = False) -> InteractiveJson:
return InteractiveJson(tree=JsonTree(d, strict=strict))
5 changes: 1 addition & 4 deletions lighttree/interactive.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import unicodedata

Expand Down Expand Up @@ -32,7 +29,7 @@ def _coerce_attr(attr: Any) -> Union[str, None]:
return None


class Obj(object):
class Obj:
"""Object class that allows to get items both by attribute `__getattribute__` access: `obj.attribute` or by dict
`__getitem__` access:
>>> obj = Obj(key='value')
Expand Down
13 changes: 6 additions & 7 deletions lighttree/node.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import uuid
from typing import Optional, Any, Tuple, Union
from typing import Optional, Any, Tuple

NodeId = str


class Node(object):
def __init__(
self,
identifier: Optional[str] = None,
identifier: Optional[NodeId] = None,
auto_uuid: bool = True,
keyed: bool = True,
accept_children: bool = True,
repr_: Optional[Union[str, float]] = None,
repr_: Optional[str] = None,
data: Any = None,
) -> None:
"""
Expand All @@ -25,7 +24,7 @@ def __init__(
self.identifier = identifier
self.keyed = keyed
self.accept_children = accept_children
self.repr = str(repr_) if repr_ is not None else None
self.repr = repr_
self.data = data

def line_repr(self, depth: int, **kwargs: Any) -> Tuple[str, str]:
Expand Down
Loading

0 comments on commit fed7c54

Please sign in to comment.