def validate_loop(doctype, name, lft, rgt):
	if name in frappe.db.sql_list("""select name from `tab%s` where lft <= %s and rgt >= %s""" % (doctype,
		"%s", "%s"), (lft, rgt)):
		frappe.throw(_("Item cannot be added to its own descendents"), NestedSetRecursionError)
check if item not an ancestor (loop)
dataset/ETHPy150Open frappe/frappe/frappe/utils/nestedset.py/validate_loop