Skip to main content

Python module parsing

Structured static views of Python modules, definitions, docstrings, literals, and @patch targets.

parse_py and parse_py_file build a lightweight PyMod tree from Python source without importing or executing it. Each node exposes its docstring and live ast.Constant node, child classes and functions in source order, dotted qualname, source span, and decorator names; PyMod adds top-level assignments and literal values.

from fastcore.test import *
from tempfile import TemporaryDirectory

Modules and definitions


source

decor_id

def decor_id(
    d:ast.AST, # Decorator expression from `node.decorator_list`
)->str:

Name of decorator AST node d, whether bare, called, or dotted

decor_id normalises bare (@patch), called (@patch(as_prop=True)), and dotted (@fastcore.patch, @x.setter) decorator nodes to their final identifier, returning '' for arbitrary expressions:

test_eq([decor_id(d) for d in ast.parse('@a\n@b(1)\n@x.y\n@c[0]()\ndef f(): pass').body[0].decorator_list], ['a', 'b', 'y', ''])

source

PyDef

def PyDef(
    node, prefix:str='', src:NoneType=None
):

Structured view of a Python module, class, or function AST node

PyDef wraps a module, class, or function AST node, collecting its direct child defs (classes and funcs/methods), cleaned doc and live doc_node, decorator names, and line span. all_defs walks direct bodies recursively in source order, and source slices from the first decorator through end_lineno when source text was supplied:

d = PyDef(ast.parse('class C:\n    "Doc"\n    def m(self): pass'))
test_eq((d.classes[0].doc, d.all_defs.attrgot('qualname')), ('Doc', ['C', 'C.m']))

source

PyMod

def PyMod(
    node, src:NoneType=None
):

Structured view of a parsed Python module: docstring, definitions, assignments, and literals


source

parse_py

def parse_py(
    src:str | ast.Module, # Python source string or pre-parsed `ast.Module`
    safe:bool=False, # Return `None` on parse error instead of raising?
)->__main__.PyMod | None:

Parse Python source src (or wrap an ast.Module) into a PyMod

parse_py walks direct module, class, and function bodies into PyDef nodes, keeping order and repeated names (such as @property / @x.setter) via L. Each node’s doc is cleaned with inspect.cleandoc, while doc_node holds the live ast.Constant for line spans or AST mutation, and source slices from the first decorator through end_lineno:

SRC = """"Demo module."
__docs__ = {'Docs': ['demo.core']}
__base_url__: str = 'https://example.com'
EMPTY = None
x = 1
x = compute()
__all__ = ['Box']
__all__ += ['run']
a, b = 1, 2
unassigned: int

class Box:
    "A container"
    @property
    def val(self): return 1
    @val.setter
    def val(self, v): pass
    async def fetch(self):
        "Load asynchronously"
        def _helper(): pass

def _priv(): pass

@fastcore.wraps(Box)
async def run():
    "Run it"
    pass
"""
m = parse_py(SRC)
test_eq(m.doc, 'Demo module.')
test_eq(m.doc_node.end_lineno, 1)
test_eq(m.defs.attrgot('qualname'), ['Box', '_priv', 'run'])
test_eq(m.all_defs.attrgot('qualname'), ['Box', 'Box.val', 'Box.val', 'Box.fetch', 'Box.fetch._helper', '_priv', 'run'])
test_eq([d.name for d in m.defs if d.is_public], ['Box', 'run'])
test_eq(m.classes[0].methods.attrgot('decos'), [['property'], ['setter'], []])
assert m.funcs[-1].source.startswith('@fastcore.wraps(Box)\nasync def run():')
m.all_defs

PyMod.assigns records every top-level assigned name (including annotated, augmented, and unpacked targets), while PyMod.literals keeps only values evaluable with ast.literal_eval and invalidates a name if a later statement reassigns or augments it non-literally:

test_eq(list(m.assigns), ['__docs__', '__base_url__', 'EMPTY', 'x', '__all__', 'a', 'b'])
test_eq(m.literals, dict(__docs__={'Docs': ['demo.core']}, __base_url__='https://example.com', EMPTY=None))
assert parse_py(ast.parse('def f(): pass')).funcs[0].source is None
test_is(parse_py('def broken(', safe=True), None)
with expect_fail(SyntaxError): parse_py('def broken(')

source

parse_py_file

def parse_py_file(
    path:str | pathlib.Path, # Path to a Python source file
    safe:bool=False, # Return `None` on read or parse error instead of raising?
)->__main__.PyMod | None:

Read and parse a Python file at path into a PyMod

parse_py_file reads a UTF-8 file path rather than source text, avoiding the trap where a string path such as 'pkg/mod.py' would otherwise parse as a valid division expression:

with TemporaryDirectory() as td:
    p = Path(td)/'sample.py'
    p.write_text('"Hi"\ndef f(): pass\n', encoding='utf-8')
    mf = parse_py_file(p)
    test_eq((mf.doc, mf.funcs[0].name), ('Hi', 'f'))
    (Path(td)/'bad.py').write_text('def (:\n', encoding='utf-8')
    test_is(parse_py_file(Path(td)/'bad.py', safe=True), None)
    test_is(parse_py_file(Path(td)/'missing.py', safe=True), None)

@patch targets

patch_targets reads the target class names of @patch and @patch_to functions (sync or async), expanding union (A | B) and tuple annotations and handling positional-only self:


source

patch_targets

def patch_targets(
    o, # `PyDef` or AST node to inspect
)->list[str]:

Target class names for a @patch or @patch_to function, or []

PSRC = r'''
@patch
def a(self: Foo): pass
@fastcore.patch(as_prop=True)
async def b(self: A | mod.B, /): pass
@patch
def c(self: (X, Y)): pass
@patch_to(cls=Z)
def d(self): pass
@patch
def e(self): pass
def plain(): pass
class Cls: pass
'''
pm = parse_py(PSRC)
test_eq([patch_targets(d) for d in pm.defs], [['Foo'], ['A', 'mod.B'], ['X', 'Y'], ['Z'], [], [], []])
test_eq(patch_targets(pm.funcs[0].node), ['Foo'])