Repository navigation
Releases
v2.9.0 — Toponymy
Changed
- A file Python would not compile is now left out with a warning, instead of aborting the whole run.
- The warning names the file and line, and the rest of the files are analyzed as usual.
- Besides syntax errors, this covers scoping errors such as a
nonlocalafter an assignment, which code using syntactic macros can contain before expansion. --module-levelskips only what does not parse, since it does not check scopes.
Fixed
-
Calls and names inside an assignment target are now recorded as uses.
- In
table[slot()] = 1andmake().attr = 2, the calls toslotandmakewere missing from the graph, as was the read oftable.
- In
-
Lambdas and comprehensions are now always analyzed in their own scopes (#142).
- Wherever pyan met two lambdas in a different order than Python does, they could trade scopes. A nested lambda then aborted the run with
ValueError: Unknown scope, as in the reportedx.do(lambda: ...).do(lambda a: a.do(lambda: ...)). - Affected: method chains, assignments with a lambda on both sides of the
=, a lambda among a function's defaults and another in its decorator, a lambda default of a lambda, and lambdas in annotations and class bases. - Without a nested lambda nothing crashed, but on Python 3.12+ a lambda following a comprehension that held one could share that lambda's scope, and pick up its parameters.
- Wherever pyan met two lambdas in a different order than Python does, they could trade scopes. A nested lambda then aborted the run with
v2.8.1
Hotfix release.
Fixed
-
--module-levelno longer drops every dependency on a package itself. A package's__init__.pywas registered under the namepkg.__init__, whileimport pkgrecords a dependency onpkg— so the edge pointed at a module that, as far as the graph was concerned, did not exist, and was discarded without a warning. Both directions went: a module importing a name re-exported frompkg/__init__.pyshowed no dependency at all, and the package's own imports vanished with the node they started from.- The
__init__is now drawn as the package, under the namepkg.--initstill draws it separately aspkg.__init__, together with the implicit dependency every module under the package has on it — which is what the default omits, and what it was trying to omit all along. - An
__init__.pynaming its own package —from harbor import quay, written inharbor/__init__.py— resolves to the module the import is written in, and draws nothing. A module does not depend on itself. - Still missed:
from . import thing, wherethingis a name defined in__init__.pyrather than a submodule. Recorded inTODO_DEFERRED.md, along with the cycle report naming a packagepkg.__init__where the graph now sayspkg.
- The
-
Ungrouped output now names a module by its dotted path.
--module-levellabelled modules with their short name, so in a project with several packages holding autilsor anapp, distinct modules printed identically and--textran their entries together as though they were one. Grouped output was unaffected, the cluster title supplying the package; so was the call graph, which builds module nodes with the whole path in the name. That is now the form both use. -
A misspelled option is now an error instead of being ignored. Filenames are whatever the argument parser does not claim, so
--with-init— a plausible misspelling of--init— was taken for a glob, matched nothing, and left pyan running with the setting the user was trying to change. Both the call graph and--module-levelwere affected. A glob matching no files is likewise an error in--module-levelnow, as it already was for the call graph. -
What the graph leaves out now describes grouped output correctly, and gives an example of each rule. Every module is drawn as a box under
--grouped; the README said a module without members stays a plain node, which it does not — an empty__init__.pygets a box holding<module>alone. Only the first of the culling rules came with an example, so the rest have one now.- It also warns that folding a lambda or comprehension into its enclosing function hides a scope boundary Python really has, so a call made inside one cannot be told from a call in the function body. Name resolution is unaffected — a lambda parameter or comprehension target shadows the enclosing binding, as it should.
v2.8.0 — Ground truth
New
- A parameter's type annotation is now treated as its type, so
def f(obj: Thing): obj.method()draws an edge toThing.method. A local already behaved this way —thing = Thing(); thing.method()always resolved — and an annotation is the one place a codebase states the type on purpose, which left the asymmetry hard to defend.- It is a static reading, and the value that arrives may be an overriding subclass.
--ignore-parameter-annotationsrestores the previous behaviour, as doesuse_parameter_annotations=Falseincreate_callgraph()andCallGraphVisitor. - Classes and modules bind — for both, the scope pyan resolves attributes against is the attribute namespace. A string annotation,
Optional[X], or a union resolves to nothing. *args/**kwargsdo not bind, being a tuple and a dict, but subscripting either does —items[0]for*items: Thing,opts["k"]for**opts: Thing— since one element is what the annotation describes.
- It is a static reading, and the value that arrives may be an overriding subclass.
Fixed
-
Reading a module-level constant now reaches the constant, not its type.
LIMIT = 42bound the name to a Node standing forint, so a read drew an edge toint— never drawn, builtins not being in the analyzed set — and the constant, referenced by nothing, was dropped as unused. Most visibly this swallowed enum members:Color.REDis a name bound to a literal, so every member access resolved tostr. Container constants were already correct, a dict or list literal having never bound a type. -
A lambda inside a lambda no longer aborts the analysis. The inner scope was registered under a name the visitor never asks for, so any file containing one failed with
ValueError: Unknown scope, taking the whole run with it — a single occurrence in a 328-file project meant no graph at all. The shape is ordinary: a test stub whose lambda builds an object from another lambda.- The same crash hit a lambda inside a comprehension on Python 3.12+, where PEP 709 stops
symtablereporting the comprehension's table and moves the lambda's up to the enclosing function.
- The same crash hit a lambda inside a comprehension on Python 3.12+, where PEP 709 stops
-
Calls made from a nested lambda or comprehension now reach the enclosing function. Folding an anonymous scope into its parent looked the parent up by splitting the namespace at its last dot — but an anonymous scope is named in two dotted pieces (
lambda.0), so for anything nested the call was folded onto a node nothing else referenced and vanished from the graph. A function whose only call tohelperwent through two levels of lambda appeared to call nothing. -
A call to an overridden method is no longer dropped when the caller also calls the base version. A postprocessing stage removed the more specific of two same-named uses edges whenever one class inherited the other, deleting a real call site: a function calling both
ASTMarker(...)and a locally definedTagged(ASTMarker)lost its edge toTagged.__init__. Attribute lookup returns one target per call site, and the stage excluded wildcards by construction, so it could never reach the ambiguous case it was written for — it has been removed.
Changed
-
Analyzing a large project is much faster — 49s to 16s on a 94k-line, 328-file codebase, with byte-identical output. In the analyzer, what was a linear scan over the whole graph is now an O(1) table lookup.
-
Uses edges that a more specific edge already conveys are now dropped. A bare
importproduces a uses edge whether or not the name is ever referenced, so a module node accumulated one per imported name — and in a graph that also shows functions, each ran parallel to the edges of the functions using it, from a node drawn right beside them. Two shapes are culled: a module's edge to a target that a function or class defined in that same module also uses, and a module's edge to another module it also reaches into. Only uses edges — a module'sdefinesedges to its own functions are never affected. (#140)- Edges that nothing else records are kept — a module-level use no function reproduces (
router = make_router()), and an import whose name is never referenced. - A module-level view is unaffected: under
--depth 0the finer edge collapses back onto the same pair, so no dependency disappears. --keep-subsumed-edgesrestores the raw edge set, as doescull_subsumed_edges=Falseincreate_callgraph()andCallGraphVisitor.
- Edges that nothing else records are kept — a module-level use no function reproduces (
-
A grouped graph no longer draws each module twice. Under
--grouped/--nested-groups, a module with members was drawn both as the cluster holding them and as an ellipse beside it carrying the same label. The cluster is the module, so the node now sits inside it, labelled<module>after the module-level code object CPython names the same way. (#140)- Every module is drawn as a box, whether or not it has members, so a module's appearance no longer depends on its contents. A package with an empty
__init__.pygets a box holding<module>alone. <module>itself appears where the module body uses something, where something uses the module, or where it is the only node its box would hold. A module that merely contains definitions is left to its members.- A module's defines edges to its own members are no longer drawn either, the box having already said it.
- Ungrouped output is unchanged: module nodes keep their dotted names and their defines edges, which are then the only indication of what contains what.
- Every module is drawn as a box, whether or not it has members, so a module's appearance no longer depends on its contents. A package with an empty
-
The rules governing what pyan omits from a graph are now documented, under What the graph leaves out in the README.
v2.7.0 — Triangulation
Fixed
- pyan now runs on Python 3.15. Two unrelated breakages, both in how the analyzer reads the interpreter's own structures rather than in any one language feature.
symtablerenamed the anonymous scopes it reports so they agree with the corresponding code objects:lambdabecame<lambda>,genexprbecame<genexpr>. pyan looked them up under the old names, so any module containing a lambda failed withValueError: Unknown scope. Scope names in the output are unchanged (stillmymodule.make_adder.lambda.0), so a project's call graph does not depend on which Python generated it.- Dict-comprehension unpacking (
{**mapping for x in xs}, new in 3.15) parses to aDictCompwhosevaluefield isNone, and the analyzer visited that field unconditionally — so analyzing a codebase containing one raisedAttributeError. Starred comprehension elements ([*items for item in ...]) and lazy imports (lazy import x) needed no change.
Changed
requires-pythonnow declares an upper bound,>=3.10,<3.16. pyan reads the AST and symbol table directly, so a new Python release can break it in ways a version-agnostic package never sees — as 3.15 did, twice. The ceiling means a future Python has to be tested and released for, rather than silently installed onto.
Version 2.6.2
Hotfix.
Fixed
--module-levelno longer drops modules that import nothing, along with every edge into them. A module with noimportstatements was never registered in the analyzed set, so it received no node — andprepare_graphthen discarded each dependency edge pointing at it, with no warning. Leaf modules (constants, small helpers, plain dataclass definitions) are exactly that shape, so a module dependency graph could omit real dependencies while looking perfectly clean. The call-graph mode was unaffected. (#138)
v2.6.1
Hotfix release.
Fixed
- Wildcard expansion no longer invents false edges to same-named definitions in the same module. An attribute call on an imported-but-unanalyzed module (e.g.
othermod.cache()) fell back to a*.cachewildcard, whichexpand_unknownsthen bound to any same-named definition whose module counts as imported — and since a module always "imports" itself, it wired a spurious edge to a localcache(). Expansion now fires only when the name actually appears as a bare reference in the source scope, so attribute accesses no longer leak into unrelated same-name functions. (#134)
v2.6.0 — Cadastre
New features
- Module-level name bindings now produce graph Nodes. Every module-level assignment (e.g.
CONSTANT = 42,LOGGER = logging.getLogger(__name__),store = _NS()) creates a definedFlavor.NAMENode at the bound dotted path.from mymod import xnow resolves to the actual binding instead of contracting to a wildcard, and the #127 attribute-fallback lands on the specific binding rather than climbing all the way to the enclosing module. Function-locals are unchanged — they stay as scope-only bindings to keep the graph readable. Edgeless NAME Nodes (module constants nobody imports) are suppressed from the rendered output by default; they remain in the analyzer's graph for cross-module resolution. - Namespace-style modules now resolve attribute access to the kwarg's target. When the rhs of a binding is
Call(func=...)whose resolved import origin is in the built-in registry (unpythonic.env.env, top-level re-exportunpythonic.env,types.SimpleNamespace,argparse.Namespace), the LHS is upgraded toFlavor.NAMESPACE_OBJECTand its scope is populated with the call's keyword arguments. Externalconfig.thingyresolves directly to whatever was passed asthingy=, bypassing the #127 module-level fallback. Recognised at all four binding sites:config = env(...),config: Env = env(...), walrus(config := env(...)), andwith env(...) as config:. Staged formconfig = env(); config.a = baais also covered (later attribute writes populate the namespace's scope through the existingset_attributemachinery).setattr(config, name, value)writes are recognised when name is a string literal, a name bound to a string literal in any scope reachable from the call site, or an imported name resolving to a string literal in another module. (#129) --namespace-constructor FQNregisters an extra namespace-constructor beyond the built-in registry (e.g.--namespace-constructor mylib.MyNamespace). Repeatable, or comma-separated. Threaded through to thecreate_callgraphAPI asnamespace_constructors=[...]. Supplying the option emits a one-shot stderr nudge inviting the user to file an issue if their constructor is reasonably common, so the built-in registry can grow from observed real-world use. (#129)
Bug fixes
- Cross-module attribute reads on namespace-style modules now produce uses edges. A module whose public surface is a runtime-built object (
SimpleNamespace,unpythonic.env.env, a smallclass _NS: pass; store = _NS()shim) used to appear as an isolated node even when it was central to the subsystem — everystore.datasetaccess landed on a synthetic ATTRIBUTE node that visgraph dropped as undefined. The analyzer now also emits an edge to the immediate defined parent of the obj (typically the exporting module) when the attribute itself can't be resolved. Symmetric for attribute writes (store.flag = value). One-level only — does not climb through unanalyzed packages, and within-scope self-references are suppressed (a method reading an undefined attribute on its own class, or a function reading module-level state in its own module, is just normal scoping). Generalizes the existing class-fallback (Enum members, class constants) introduced in 2.4.0. (#127) - Advisory when
infer_rootmay have misidentified the package root. Two ambiguous situations now emit a warning suggesting--root: (1) inference walked up at least one package level and stopped at a directory that has neither__init__.pynor a project-root marker (pyproject.toml,setup.py,setup.cfg) — consistent with a top-level PEP 420 namespace package; (2) inference didn't walk up at all but the input directory's parent has__init__.py— consistent with the user feeding pyan the contents of a namespace subpackage (e.g.pyan3 pkg/sub_ns/*.pywheresub_ns/has no__init__.py), which would otherwise silently produce bare module names and broken relative imports. Auto-walking further is unsafe — the same filesystem shapes also occur for workspace directories liketests/orexamples/— so the choice is left to the user. The--roothelp text now also mentions the namespace-package case explicitly. (#128)
Internal
analyzer.pydecomposed. Graph state and post-analysis query API extracted topyan.callgraph; postprocessing pipeline topyan.postprocessor; NAMESPACE_OBJECT pattern recognizers topyan.recognizers. Public API (create_callgraph,create_modulegraph,main) unchanged.- Test suite reorganised.
test_features.pysplit into per-concern files (test_classes.py,test_functions.py,test_iteration.py,test_async_context.py,test_match.py,test_assignments.py,test_imports.py,test_type_params.py,test_misc.py). - Flavor rename:
Flavor.NAMESPACE(synthetic structural marker for module/class/function scope bookkeeping) is nowFlavor.SCOPE. The newFlavor.NAMESPACE_OBJECTrepresents a runtime namespace value (anenvinstance, aSimpleNamespaceinstance) — aNAMEwith a populated scope listing its statically-visible attributes. The Node represents the scope; theScopeclass implements one — same concept at two layers.
v2.5.0 — Legend
New features
- Wildcard imports now resolve to actual targets.
from pkg import *is desugared at analysis time against the target package's__all__when declared as a literal list/tuple of strings, and against the public-names rule (every module-scope name not starting with_) otherwise. Names reached via wildcard — including those re-exported through__init__.py— now appear as concrete edges in the call graph instead of as spurious*.*residue at the importer's module level. Non-literal__all__forms (augmented assignment, dynamic construction) fall back to the public-names rule with a debug log. (#126)
Internal
- Prescan phase added before the two visitor passes.
CallGraphVisitor.processnow does a lightweight scope +__all__walk over every input file up front, so cross-module metadata is fully populated before pass 1. This makes wildcard desugaring order-independent — the consumer of a wildcard import no longer has to appear after the exporting package in the filename list.
v2.4.3
Bug fixes
- Names referenced inside a decorator's arguments are now attributed to the decorated function, not only to the enclosing module. Previously, a function decorated with e.g.
@app.get("/x", dependencies=[Depends(Guard())])showed no uses ofDependsorGuard— those edges landed on the module instead. The function now also gets a uses edge to each target referenced in its decorator arguments, mirroring the existing treatment of default values. (#125 — thanks @doctorgu) - Class decorators are now analyzed — previously
visit_ClassDefignoreddecorator_listentirely, so@dataclassor@register(kind="x")on a class produced no uses edges anywhere. Class decorators now behave like function decorators: the decorator expression is visited at module scope, and referenced names are also attributed to the decorated class.
v2.4.2 — Benchmark
A surveyor's benchmark is a reference mark — a fixed point of known position, cut into rock, that everything else can be measured against. This release is exactly that: no new user-visible features, but the Sphinx extension is now covered by an end-to-end integration test, so what was previously advertised is now verified.
Thanks to @BlocksecPHD for contributing the test (#124, closes #114).
Internal
- Build system migrated from hatchling+uv to PDM (
pdm-backend). No user-visible changes;pip install pyan3works as before. - Sphinx extension: end-to-end integration test covering
sphinx-build, the.. callgraph::directive, pan/zoom HTML wiring, and directive option propagation. Uses an in-testdotstub, so CI needs no system Graphviz. Closes #114. (#124 — thanks @BlocksecPHD)
See CHANGELOG.md for the full history.