There are variations, like
import ast
code = """
import datetime
datetime.datetime.now()
"""
tree = ast.parse(code)
print(ast.dump(tree, indent=2))
the AST prints
Module(
body=[
Import(
names=[
alias(name='datetime')]),
Expr(
value=Call(
func=Attribute(
value=Attribute(
value=Name(id='datetime', ctx=Load()),
attr='datetime',
ctx=Load()),
attr='now',
ctx=Load()),
args=[],
keywords=[]))],
type_ignores=[])
Or using import from
import ast
code = """
from datetime import datetime
datetime.now()
"""
tree = ast.parse(code)
print(ast.dump(tree, indent=2))
Module(
body=[
ImportFrom(
module='datetime',
names=[
alias(name='datetime')],
level=0),
Expr(
value=Call(
func=Attribute(
value=Name(id='datetime', ctx=Load()),
attr='now',
ctx=Load()),
args=[],
keywords=[]))],
type_ignores=[])
Is there a built-in way to determine what module the function call belongs to? That is find all function calls datetime.now()
from datetime
module?