# Callback in Python igraph Traversal Algorithms

**URL:** https://igraph.discourse.group/t/callback-in-python-igraph-traversal-algorithms/1517
**Category:** Usage
**Tags:** Python
**Created:** [26 March 2023 06:25 UTC](https://igraph.discourse.group/t/callback-in-python-igraph-traversal-algorithms/1517 "2023-03-26T06:25:13Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![nparham](https://yyz2.discourse-cdn.com/free1/user_avatar/igraph.discourse.group/nparham/32/864_2.png) [@nparham](https://igraph.discourse.group/u/nparham)
#### Post date: [26 March 2023 06:25 UTC](https://igraph.discourse.group/t/callback-in-python-igraph-traversal-algorithms/1517/1 "2023-03-26T06:25:13Z")

</div>

Is it not possible to specify a callback for BFS/DFS in igraph via the Python API? If not, is this not a feature on purpose? I am wondering why R seems to have more functionality than Python with respect to igraph features.

---

<div class="post-metadata">

### Author: ![tamas](https://yyz2.discourse-cdn.com/free1/user_avatar/igraph.discourse.group/tamas/32/1261_2.png) [@tamas](https://igraph.discourse.group/u/tamas)
#### Post date: [27 March 2023 17:54 UTC](https://igraph.discourse.group/t/callback-in-python-igraph-traversal-algorithms/1517/2 "2023-03-27T17:54:02Z")

</div>

Callbacks aren’t idiomatic Python so the Python interface provides `Graph.bfsiter()` and `Graph.dfsiter()` instead, both of which probably allow you to achieve the same thing using a `for` loop. E.g., something like:

```python
g = Graph.GRG(100, 0.2)
for vertex, dist, parent in g.dfsiter(0, advanced=True):
    if parent is None:
        print(f"DFS traversal starts at vertex {vertex.index}")
    else:
        print(f"Vertex {vertex.index} reached at distance {dist} from vertex {parent.index}")

```

---

<div class="post-metadata">

### Author: ![ElectronicRU](https://yyz2.discourse-cdn.com/free1/user_avatar/igraph.discourse.group/electronicru/32/1206_2.png) [@ElectronicRU](https://igraph.discourse.group/u/ElectronicRU)
#### Post date: [10 June 2025 13:51 UTC](https://igraph.discourse.group/t/callback-in-python-igraph-traversal-algorithms/1517/3 "2025-06-10T13:51:25Z")

</div>

@tamas The iterator scheme is unable to perform actions upon completing a subtree, though. You could remember last visited vertex and depth, and detect when a subtree was exited based on that, but that feels even less idiomatic.
