Skip to content

fix: to_dict() returns None for non-expanded nodes - #243

Closed
gaoflow wants to merge 1 commit into
caesar0301:masterfrom
gaoflow:fix-to-dict-collapsed-node
Closed

fix: to_dict() returns None for non-expanded nodes#243
gaoflow wants to merge 1 commit into
caesar0301:masterfrom
gaoflow:fix-to-dict-collapsed-node

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 28, 2026

Copy link
Copy Markdown

Summary

Tree.to_dict() returns None when called on a node with expanded=False, instead of the expected string (tag) or dict (with children). This also breaks to_json(), which returns "null" for collapsed trees.

The root cause: when self[nid].expanded is False, the method skips the if block entirely and falls through without hitting a return statement, yielding None by default.

Reproduction:

from treelib import Tree
t = Tree()
t.create_node("Root", "root")
t.create_node("A", "a", parent="root")
t["root"].expanded = False

print(t.to_dict())    # None (expected "Root")
print(t.to_json())    # "null" (expected '"Root"')

Fix: Add an else clause to return the tag/dict-with-data when the node is not expanded, consistent with how leaf nodes (expanded=True, no children) are already handled.

All 207 existing tests pass. AI-assisted.

When a node has expanded=False, to_dict() skips the return
statement entirely, returning None instead of the expected
tag string or dict with data. This also breaks to_json() which
returns 'null' for collapsed trees.

Add else clause to handle the non-expanded case consistently
with the expanded-but-empty-children case.
@gaoflow
gaoflow requested a review from liamlundy as a code owner June 28, 2026 13:40
@liamlundy

Copy link
Copy Markdown
Collaborator

@gaoflow can you add a unit test for this case and make sure that all the tests pass?

@gaoflow

gaoflow commented Jul 26, 2026

Copy link
Copy Markdown
Author

This is already fixed on master — 700d9d7 rewrote to_dict, and the collapsed case now falls through to return ntag instead of dropping off the end.

On current master the repro gives to_dict() == "Root" and to_json() == '"Root"'; on 700d9d7~1 they were None and "null". So there is nothing left for this PR to do and it can be closed.

@liamlundy liamlundy closed this Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants