## call_stack()


Build the call tree of a function from its source, without running it.


Usage

``` python
call_stack(
    fn,
    max_depth=None,
    exclude=None,
    package_only=False,
    labels="def",
)
```


[call_stack()](call_stack.md#callgrove.call_stack) reads the function's source, finds every function it calls, and follows each of those the same way. Calls to `functools.singledispatch` functions are followed into every registered implementation, which play the part R's `UseMethod()` methods do.

Resolution is static. The function is never called. A class call is followed into the class's `__init__`, `self.method()` and `cls.method()` into the class the caller is defined in, and `Class().method()` into that method. Calls that can only be known at run time (`getattr()`, functions passed in as arguments, methods on a parameter) show as leaves or are skipped. Builtins and C extension functions have no Python source, so they are leaves too.


## Parameters


`fn: str | Callable[…, Any]`  
A dotted path such as `"json.dumps"` or `"pkg.module.Class.method"`, a bare builtin name such as `"len"`, or the function itself.

`max_depth: int | None = None`  
How many levels to expand. `None` (the default) follows every call down to a leaf or a function already visited.

`exclude: str | Iterable[str] | None = None`  
Function names to drop from the tree, such as a logging helper that appears under every node. A dropped function's children move up into its place. The root is never dropped.

`package_only: bool = ``False`  
When True, only functions from the root's own top level package are expanded. Calls into other packages and the standard library stay in the tree as leaves. Default False, which follows every call.

`labels: str = ``"def"`  
`"def"` (the default) labels a function from the root's own package by its definition name (`Model.fit`), and everything else by the text at the call site (`re.sub`). `"call"` uses the call site text everywhere (`model.fit`). Nested functions are always labeled `outer.inner`.


## Returns


`CallTree`  
The root node. Print it to draw the tree.


## Examples

``` python
>>> call_stack("callgrove.CallTree.__str__")
```

█─CallTree.\_\_str\_\_ ├─\_label └─█─\_draw ├─enumerate ├─len ├─\_label └─\_draw

``` python
>>> call_stack("callgrove.call_tree_dir", max_depth=1, package_only=True)
```

█─call_tree_dir …
