Skip to content

Commit

Permalink
new tip
Browse files Browse the repository at this point in the history
  • Loading branch information
bbelderbos committed Oct 5, 2023
1 parent 159f5fd commit 9413ba9
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ This file gets generated by [this script](index.py).
## Ast

- [Code uses list comprehensions?](notes/20230215131208.md)
- [Get all callables from a file](notes/20231005125327.md)
- [Parse import statements](notes/20230816183323.md)
- [String to object](notes/20221214133347.md)

Expand Down
37 changes: 37 additions & 0 deletions notes/20231005125327.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Get all callables from a file

You can conveniently use the `ast` module for this:

```
import ast
def get_callables_from_file(filename):
with open(filename, 'r') as f:
content = f.read()
tree = ast.parse(content)
callables = []
def visit_callables(node):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
callables.append(node.name)
elif isinstance(node, ast.ClassDef):
# Inside a class, continue checking for methods
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
callables.append(f"{node.name}.{child.name}")
for child in ast.iter_child_nodes(node):
visit_callables(child)
visit_callables(tree)
return callables
# Example usage:
filename = 'path_to_your_file.py'
print(get_callables_from_file(filename))
```

#ast

0 comments on commit 9413ba9

Please sign in to comment.