{"record":{"id":"c3c8d1e8a18768b2","repo":"TheAlgorithms/Python","slug":"value-must-be-an-integer","errorCode":null,"errorMessage":"Value must be an integer.","messagePattern":"Value must be an integer\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"data_structures/binary_tree/serialize_deserialize_binary_tree.py","lineNumber":24,"sourceCode":"\n@dataclass\nclass TreeNode:\n    \"\"\"\n    A binary tree node has a value, left child, and right child.\n\n    Props:\n        value: The value of the node.\n        left: The left child of the node.\n        right: The right child of the node.\n    \"\"\"\n\n    value: int = 0\n    left: TreeNode | None = None\n    right: TreeNode | None = None\n\n    def __post_init__(self):\n        if not isinstance(self.value, int):\n            raise TypeError(\"Value must be an integer.\")\n\n    def __iter__(self) -> Iterator[TreeNode]:\n        \"\"\"\n        Iterate through the tree in preorder.\n\n        Returns:\n            An iterator of the tree nodes.\n\n        >>> list(TreeNode(1))\n        [1,null,null]\n        >>> tuple(TreeNode(1, TreeNode(2), TreeNode(3)))\n        (1,2,null,null,3,null,null, 2,null,null, 3,null,null)\n        \"\"\"\n        yield self\n        yield from self.left or ()\n        yield from self.right or ()\n\n    def __len__(self) -> int:","sourceCodeStart":6,"sourceCodeEnd":42,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/binary_tree/serialize_deserialize_binary_tree.py#L6-L42","documentation":"Raised by TreeNode.__post_init__ (dataclasses/serialize_deserialize_binary_tree.py) when the value field is not an int. The dataclass validates its value immediately after construction, so TreeNode('1'), TreeNode(1.0), or TreeNode(None) all fail with TypeError. Note bool is an int subclass and passes; the check is isinstance(self.value, int), so True/False are accepted.","triggerScenarios":"TreeNode('5') with a string (typical when building nodes from unparsed text/JSON); TreeNode(1.5) from float math; TreeNode(None) as a 'missing' marker; passing a numpy int64 (isinstance check may pass since it subclasses int in some builds, but plain object dtype values will fail).","commonSituations":"Deserializing JSON where numbers arrive as strings; reading node values from CSV/text without int() conversion; mixing float coordinates into a tree meant for integer labels.","solutions":["Convert before constructing: TreeNode(int(raw)) for string input","Sanitize at the parse boundary: `int(value.strip())` right after reading tokens","If non-int payloads are legitimate, copy the dataclass and widen the field type instead of fighting the guard"],"exampleFix":"# before\nnode = TreeNode('5')  # TypeError\n\n# after\nnode = TreeNode(int('5'))","handlingStrategy":"type-guard","validationCode":"from data_structures.binary_tree.serialize_deserialize_binary_tree import TreeNode\n\nnode = TreeNode(value) if isinstance(value, int) and not isinstance(value, bool) else TreeNode(int(value))","typeGuard":"def is_int_value(v: object) -> bool:\n    \"\"\"True for real ints (excluding bool, which the dataclass accepts).\"\"\"\n    return isinstance(v, int)","tryCatchPattern":"try:\n    node = TreeNode(raw)\nexcept TypeError:\n    node = TreeNode(int(raw))  # coerce string/float payloads","preventionTips":["Convert to int at the parse boundary (int(x.strip()) for text/CSV tokens)","Do not feed JSON string numbers straight into TreeNode","Remember bool passes the check; normalize True/False if they leak in"],"tags":["type-check","dataclass","serialization","type-error"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}