Add match_filter and import_filter hooks to Restructure

MA
4d ago
+98-1

Restructure accepts two optional callables:

  • match_filter(pymodule, match) is called for every match found in a module, and only the matches it accepts are restructured;
  • import_filter(resource, imports) selects which of imports are added to a changed module.

Today a client that wants to skip some matches (for example matches inside code it must not touch) or reuse an import the module already has has to override the private _compute_changes and _add_imports. Both hooks default to None, so existing callers are unaffected.

The hook type aliases (MatchFilter, ImportFilter) are defined at module level, so typing.get_type_hints(Restructure.__init__) resolves.

Tests in restructuretest.py cover filtering matches, filtering imports, and the runtime annotations. Tested locally on Python 3.10, 3.11, 3.13 and 3.14.