Skip to content

nodes

nodes

Attributes

BINARY_MIN_LENGTH = 64 module-attribute

COLOR_RE = re.compile('^#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$') module-attribute

CONTAINER_KINDS = (Kind.DICT, Kind.LIST) module-attribute

JsonValue = typing.Any module-attribute

SWITCHABLE_KINDS = (Kind.NULL, Kind.BOOL, Kind.INT, Kind.FLOAT, Kind.STR, Kind.COLOR, Kind.LIST, Kind.DICT) module-attribute

Classes

JsonNode(key, value=None, parent=None)

A node of the JSON tree: leaf holds a value, containers hold children.

Initialize the node.

Parameters:

Name Type Description Default
key str | int | None

Dict key or list index; None for the root.

required
value JsonValue

The value; containers get child nodes.

None
parent JsonNode | None

The parent node.

None
Source code in src/json_config_qt/tree/nodes.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def __init__(
    self,
    key: str | int | None,
    value: JsonValue = None,
    parent: JsonNode | None = None,
):
    """Initialize the node.

    Args:
        key (str | int | None): Dict key or list index; None for the root.
        value (JsonValue, optional): The value; containers get child nodes.
        parent (JsonNode | None, optional): The parent node.
    """
    self.key = key
    self.parent = parent
    self.children: list[JsonNode] = []
    self.value: JsonValue = None
    self.kind = Kind.NULL
    self.assign(value)
Attributes
children = [] instance-attribute
is_container property

Return whether this node is a dict or a list.

key = key instance-attribute
kind = Kind.NULL instance-attribute
parent = parent instance-attribute
row property

Return this node's position within its parent's children.

value = None instance-attribute
Methods:
assign(value)

Replace this node's content with value (rebuilding children).

Source code in src/json_config_qt/tree/nodes.py
123
124
125
126
127
128
129
130
131
132
133
def assign(self, value: JsonValue) -> None:
    """Replace this node's content with *value* (rebuilding children)."""
    self.kind = kind_of(value)
    self.children = []
    self.value = None
    if isinstance(value, dict):
        self.children = [JsonNode(k, v, self) for k, v in value.items()]
    elif isinstance(value, list):
        self.children = [JsonNode(i, v, self) for i, v in enumerate(value)]
    else:
        self.value = value
renumber()

Re-index list children after an insertion or removal.

Source code in src/json_config_qt/tree/nodes.py
135
136
137
138
139
def renumber(self) -> None:
    """Re-index list children after an insertion or removal."""
    if self.kind is Kind.LIST:
        for index, child in enumerate(self.children):
            child.key = index
to_python()

Rebuild the plain JSON value of this subtree.

Source code in src/json_config_qt/tree/nodes.py
141
142
143
144
145
146
147
def to_python(self) -> JsonValue:
    """Rebuild the plain JSON value of this subtree."""
    if self.kind is Kind.DICT:
        return {child.key: child.to_python() for child in self.children}
    if self.kind is Kind.LIST:
        return [child.to_python() for child in self.children]
    return self.value

Kind

Bases: StrEnum

The type of a JSON value as presented to the user.

Attributes
BINARY = 'binary' class-attribute instance-attribute
BOOL = 'bool' class-attribute instance-attribute
COLOR = 'color' class-attribute instance-attribute
DICT = 'dict' class-attribute instance-attribute
FLOAT = 'float' class-attribute instance-attribute
INT = 'int' class-attribute instance-attribute
LIST = 'list' class-attribute instance-attribute
NULL = 'null' class-attribute instance-attribute
STR = 'str' class-attribute instance-attribute

Functions:

default_value(kind)

Return the default JSON value for kind.

Source code in src/json_config_qt/tree/nodes.py
41
42
43
44
45
46
47
48
49
50
51
52
53
def default_value(kind: Kind) -> JsonValue:
    """Return the default JSON value for *kind*."""
    return {
        Kind.DICT: dict,
        Kind.LIST: list,
        Kind.BOOL: lambda: False,
        Kind.INT: lambda: 0,
        Kind.FLOAT: lambda: 0.0,
        Kind.STR: str,
        Kind.COLOR: lambda: "#ffffff",
        Kind.BINARY: str,
        Kind.NULL: lambda: None,
    }[kind]()

is_binary_string(text)

Return whether text looks like an encoded binary blob (base64).

Source code in src/json_config_qt/tree/nodes.py
56
57
58
59
60
61
62
63
64
def is_binary_string(text: str) -> bool:
    """Return whether *text* looks like an encoded binary blob (base64)."""
    if len(text) < BINARY_MIN_LENGTH or len(text) % 4:
        return False
    try:
        base64.b64decode(text, validate=True)
    except binascii.Error, ValueError:
        return False
    return True

kind_of(value)

Classify a JSON value.

Source code in src/json_config_qt/tree/nodes.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def kind_of(value: JsonValue) -> Kind:
    """Classify a JSON value."""
    if value is None:
        return Kind.NULL
    if isinstance(value, bool):  # before int: bool is an int subclass
        return Kind.BOOL
    if isinstance(value, int):
        return Kind.INT
    if isinstance(value, float):
        return Kind.FLOAT
    if isinstance(value, str):
        if COLOR_RE.match(value):
            return Kind.COLOR
        if is_binary_string(value):
            return Kind.BINARY
        return Kind.STR
    if isinstance(value, dict):
        return Kind.DICT
    if isinstance(value, list):
        return Kind.LIST
    raise TypeError(f"Unsupported JSON value: {value!r}")