Say I have a binary tree which contains pointers at each node going to the parent and the child, and I want to remove some part of an internal subtree, patching the remainder of the tree back together in a sensible way.
Does Python know to garbage collect the discarded piece of the subtree, even though the nodes within reference each other? I would expect this to be a capability of all languages which use garbage collection, but I don’t know enough about garbage collection to know for sure. The best I have done myself is a smart (C++) pointer system which was not smart enough to handle the case I described above.
Yes, Python will discard the unreferenced nodes in the tree.
CPython uses reference counting to do most of is garbage collection. In your case, one or more of the tree nodes will have no references left, so they will be freed. Then the nodes that were pointed to by the freed node may have no references, and those will be freed too. Recursively, all unreferenced nodes will be freed.
CPython also has a garbage collector that can collect unreferenced cycles. These can’t (easily) be detected using reference counting, but the cycle collector can identify and free them.
Other implementations of Python such as IronPython or Jython use different garbage collector schemes.