0

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?

3
  • 1
    you may also be looking for inspect docs.python.org/3/library/inspect.html Commented Apr 23, 2024 at 22:37
  • 1
    You have 3 distinctly different questions here: "Find a module's function", "determine what module the function call belongs to" and "find all function calls datetime.now() from datetime module`. Which of these is really your goal? Commented Apr 24, 2024 at 1:37
  • "determine what module the function call belongs to" would be the closest Commented Apr 24, 2024 at 16:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.