-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
159f5fd
commit 9413ba9
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |