MCPcopy Index your code
hub / github.com/joowani/binarytree / __setattr__

Method __setattr__

binarytree/__init__.py:177–230  ·  view source on GitHub ↗

Modified version of ``__setattr__`` with extra sanity checking. Class attributes **left**, **right** and **value** are validated. :param attr: Name of the class attribute. :type attr: str :param obj: Object to set. :type obj: object :raise binarytree

(self, attr: str, obj: Any)

Source from the content-addressed store, hash-verified

175 return "\n" + "\n".join((line.rstrip() for line in lines))
176
177 def __setattr__(self, attr: str, obj: Any) -> None:
178 """Modified version of ``__setattr__`` with extra sanity checking.
179
180 Class attributes **left**, **right** and **value** are validated.
181
182 :param attr: Name of the class attribute.
183 :type attr: str
184 :param obj: Object to set.
185 :type obj: object
186 :raise binarytree.exceptions.NodeTypeError: If left or right child is
187 not an instance of :class:`binarytree.Node`.
188 :raise binarytree.exceptions.NodeValueError: If node value is invalid.
189
190 **Example**:
191
192 .. doctest::
193
194 >>> from binarytree import Node
195 >>>
196 >>> node = Node(1)
197 >>> node.left = [] # doctest: +IGNORE_EXCEPTION_DETAIL
198 Traceback (most recent call last):
199 ...
200 binarytree.exceptions.NodeTypeError: Left child must be a Node instance
201
202 .. doctest::
203
204 >>> from binarytree import Node
205 >>>
206 >>> node = Node(1)
207 >>> node.val = [] # doctest: +IGNORE_EXCEPTION_DETAIL
208 Traceback (most recent call last):
209 ...
210 binarytree.exceptions.NodeValueError: node value must be a float/int/str
211 """
212 if attr == _ATTR_LEFT:
213 if obj is not None and not isinstance(obj, Node):
214 raise NodeTypeError("left child must be a Node instance")
215
216 elif attr == _ATTR_RIGHT:
217 if obj is not None and not isinstance(obj, Node):
218 raise NodeTypeError("right child must be a Node instance")
219
220 elif attr == _ATTR_VALUE:
221 if not isinstance(obj, _NODE_VAL_TYPES):
222 raise NodeValueError("node value must be a float/int/str")
223 object.__setattr__(self, _ATTR_VAL, obj)
224
225 elif attr == _ATTR_VAL:
226 if not isinstance(obj, _NODE_VAL_TYPES):
227 raise NodeValueError("node value must be a float/int/str")
228 object.__setattr__(self, _ATTR_VALUE, obj)
229
230 object.__setattr__(self, attr, obj)
231
232 def __iter__(self) -> Iterator["Node"]:
233 """Iterate through the nodes in the binary tree in level-order_.

Callers

nothing calls this directly

Calls 2

NodeTypeErrorClass · 0.90
NodeValueErrorClass · 0.90

Tested by

no test coverage detected