Skip to content

Count the names of modules imported by a string or passed as a value as used - #284

Merged
Apakottur merged 1 commit into
mainfrom
modules-reached-dynamically
Nov 22, 2026
Merged

Apakottur merged 1 commit into
mainfrom
modules-reached-dynamically

Conversation

@Apakottur

@Apakottur Apakottur commented Nov 22, 2026 •

Copy link
Copy Markdown
Owner

A module-level function, class or variable counted as used only when it was read in its module, imported, read as module.name through an imported name, listed in __all__, or looked up in globals(). When a module was reached as an object some other way (by importlib.import_module, or passed as an argument), all its names were reported. Matching every value.name read against every module-level name would fix that, but it would throw away the precision unref has over Vulture everywhere. So this PR measures first, then adds the three narrow rules the data supports.

1. Measurement

Method. I built a throwaway binary that applies the naive rule (any value.name read keeps every module-level name). I ran it and main (b785eca) with --show-transitive on the 19 projects of scripts/ecosystem.py, plus three projects known for plugin loading: celery, pelican and ansible. Then I classified what the naive rule removes, using prototype binaries for each candidate rule plus manual inspection.

The naive rule removes 4,513 findings (ansible 477, black 708, celery 114, django 405, fastapi 28, mealie 401, openlibrary 42, pelican 6, prefect 1,167, pydantic 55, pytest 7, rich 30, saleor 29, sphinx 522, sqlalchemy 363, strawberry 12, werkzeug 32, zulip 151; flask, freqtrade, full-stack-fastapi-template and starlette 0). The table below counts its 3,858 removals of module-level names; the rest are their methods and attributes.

Class Removed by naive Where Examples
(a) literal import_module("pkg.mod") / __import__ 12 ansible 11, django 1 ansible-test import_module("ansible_test._internal") then .main()
(b) literal parts in the call (f"pkg.{x}", "pkg.%s" % x, f"{pkg.__name__}.x.{y}") ~10 werkzeug, ansible werkzeug tests/live_apps/run.py: import_module(f"{name}_app").app; ansible _ansiballz/_loader.py: import_module(f'{_ansiballz.__name__}._extensions.{x}').run
(c) fully dynamic string ~525 django 112, sphinx 378 (81 setup), rich 21, zulip 9, prefect 5 django include(): getattr(import_module(urlconf), "urlpatterns") (110 test urlconfs); sphinx registry.py: getattr(import_module(extname), "setup"); prefect import_module(BROKER.value()).Publisher; rich import_module(name, "rich._unicode_data").cell_table
(d)/(e) imported module passed, aliased or stored ~178 django 132, sqlalchemy 23, ansible 11, strawberry 9 django for s in dir(global_settings): setattr(self, s, getattr(global_settings, s)), read as settings.X; ansible from ...distro import _distro as distro, distro = _system_distro or _distro; strawberry integration = fields; integration.validate_field_type(...); sqlalchemy util.preloaded: sql_traversals = _sql_traversals
(f) sys.modules[...] 0 seen sqlalchemy loads plugin_base by path into sys.modules["sqla_plugin_base"] (counted in (g))
(g) loaders outside the project, or by file path ~1,900 Alembic migrations 1,204 (prefect 940, mealie 264: upgrade, downgrade, revision...); ansible DOCUMENTATION 296 (read by path / AST); Django Command in zulip 101 (on main since #283); sphinx conf.py values 89; settings modules 28
(h) coincidental name matches ~1,600 black tests/data 624 (formatter inputs: f, x, foo); the rest are names like logger, display, run, delete. In a sample of 45 of the remaining 991, about half were dead code or test data, and the other half were false positives with other causes (decorator registration, path loaders)

Prefix-only matching (f"plugins.{x}" with a literal start) removes nothing on these projects: real code builds the name in a variable first, or starts it with a value.

2. Rules chosen

  1. Literal string → exact module. m = import_module("pkg.mod"), __import__("pkg.mod", fromlist=...) and __import__("pkg.mod") (the top package) bind m as import ... as m would. Relative strings with package=__package__/__name__ or a literal package work too. The attributes stay loose reads as well: the module can be replaced in sys.modules, as openlibrary's tests do. Without that, two test stubs became new findings.

  2. String with values → glob over module names. The literal parts of the string match module names in order, with any text between them: "apps.%s.handlers.%s" → apps.*.handlers.*, f"{name}_app" → *_app. A leading __name__ or __package__ counts as one leading dot, and pkg.__name__ as the name pkg was imported as. A name with no literal part matches any module. This rule covers (b) and (c). It is tracked like local_calls: a name assigned the call in the same scope.

  3. Module passed on → matched by name. A module of the project that is given to a function, assigned, put in a list/tuple/set/dict, or returned has its names matched by any value.name read. That is how attributes of objects are matched already, and like loose in class_members.rs. It does not count as passed when:

    • it is given to setattr/monkeypatch.setattr, patch.object, reload, isinstance, getattr or hasattr (without this, openlibrary lost 18 findings, all coincidental);
    • its package binds the same name to something else, as from .directive import directive does (strawberry's @strawberry.directive(...) made strawberry/directive.py escape).

    Modules that are only read through their names (alpha.run) stay precise.

Results on the ecosystem (merged main d95ef25 → this branch)

--show-transitive: −725, +0. ansible −26, django −245, pelican −1, prefect −6, rich −21, sphinx −378, sqlalchemy −23, strawberry −9, werkzeug −7, zulip −9; the other 12 are unchanged.

I looked at all of the removed module-level names:

  • Real false positives fixed: 721. django 110 urlpatterns + 132 global_settings values + 3 modules loaded by test strings (SessionStore...); sphinx 81 extension setup functions (+297 they reach); rich 21 cell_table; zulip 9 fixture_to_headers; prefect broker Publisher/ephemeral_subscription/break_topic; werkzeug live apps app/kwargs; ansible ansiballz extensions, distro, ansible-test main; sqlalchemy 13 MySQL type aliases (m = mysql; m.MSYear in tests), the preloaded names operator_lookup and _get_children, the mssqlpython dialect, and dml.isupdate/isdelete (called from sql/crud.py); strawberry's pydantic integration; pelican's dummy plugin register.
  • Dead code now hidden (cost of rule 3): 4. prefect server/events/stream.py logger (the module sits in a list of services, and .logger is read elsewhere; the test patches a different module, logs/stream.py); sqlalchemy testing/config.py test_schema_2 (assigned through global, only read as cfg.test_schema_2 on a Config object); sqlalchemy orm/attributes.py has_parent/init_collection (only called from tests that unref does not reach; .has_parent read on a manager keeps them).

In the default mode (no --show-transitive), sphinx shows +104. All 104 are findings on main with --show-transitive. They were hidden as transitive under the 81 setup functions, which are no longer false positives, so their own unused helpers now print. Nothing new is reported.

Precision cost, against class (h). Rules 1 and 2 add no coincidental matches on these projects once the glob is used. Before it, "any module" for f"{name}_app" kept a dead app in a werkzeug example, and f"{pkg.__name__}..." kept 5 run functions in ansible's packaging/release.py. Rule 2's real cost is for a name with no literal part: module.setup then keeps every module-level setup in the project. On these projects all such names are plugin hooks (setup, urlpatterns, register, Command). Rule 3 costs the 4 above. The naive rule would have hidden ~1,600 coincidental matches plus 624 test-data files.

Speed

scripts/benchmark.py compare against the main release binary (CPython, median of 15):

run 1 run 2
Single core +2.1% −2.5%
Multi core +1.4% +4.8%

Main against a copy of itself gave +3.2% / +0.5%, so this is noise. A first version marked passed names in a hash set and cost +3.5%; the walker now visits them directly.

Not covered

  • Loaders by file path or outside the project. Alembic migrations (1,204 findings on prefect and mealie), ansible DOCUMENTATION, Sphinx conf.py values, settings modules, sys.modules[...] = load_file(...). These belong in framework rules (Alembic would be a new one).
  • A module stored on an attribute (self.backend = import_module(...)), sys.modules["name"], and a string built in a variable before the call (name = f"pkg.{x}"; import_module(name) counts as any module rather than pkg.*; this covers zulip's webhooks and rich's unicode tables). They could be added like local_calls if precision there matters.
  • getattr(module, name) with a dynamic name, and dir(module). The module escapes, but only names read somewhere as attributes are kept.

Verification

  • New case tests/cases/modules_as_objects: plugins by f-string, relative with __package__ and f"{__name__}.{x}", an exact backend, "%s.handlers.%s", a fully dynamic extension, __import__ with fromlist, a module passed to a function, setattr/isinstance/hasattr that do not pass it, and a package whose name is rebound. Negative lines: the same names in unreached/plugin.py, apps/shop/views/orders.py (outside the glob), tools/parsing.py (never passed) and widgets/button.py are still reported.
  • docs/rules.md: a new "Modules as objects" section.
  • cargo test: pass
  • uv run pytest -c tests/pytest.ini tests: 288 passed
  • uv run prek run -a: all pass

…g, or passed on

A module-level name was used only when read in its module, imported, read as `module.name` through
an imported name, listed in `__all__` or looked up in `globals()`. A module reached another way had
all its names reported. Now:

- `module = import_module("pkg.mod")`, or `__import__` with a `fromlist`, binds `module` as
  `import pkg.mod as module` does.
- `module = import_module(<string with values>)` reads `module.name` in each module whose name
  matches the literal parts of the string, in order (`f"plugins.{name}"`, `"%s.handlers.%s"`,
  `"." + name` with `__package__`, `f"{pkg.__name__}.ext.{name}"`), or in any module when it has
  none.
- A module of the project that is passed on (given to a function, assigned, put in a container or
  returned) has its names matched by name by any read of an attribute, as attributes are. Modules
  only read by their names, or given to setattr, patch.object, reload or isinstance, stay precise.

Assisted-by: Claude:claude-opus-5-5
@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 unref | 🛠️ Build #36073072 | 📁 Comparing 3acae5b against latest (d95ef25)

  🔍 Preview build  

1 file changed
± rules/index.html

@github-actions

Copy link
Copy Markdown
Contributor

Performance

Time to check CPython v3.15.0: the median of 15 runs of each binary, run in turns.

Cores Base Head Change
Single core 1.54s 1.56s +1.2%
Multi core 1.02s 1.05s +2.9%

Ecosystem

Findings on 19 projects: 8 changed.

django: +0 -245
- django/conf/global_settings.py:17:1: unused-variable 'DEBUG'
- django/conf/global_settings.py:22:1: unused-variable 'DEBUG_PROPAGATE_EXCEPTIONS'
- django/conf/global_settings.py:31:1: unused-variable 'INTERNAL_IPS'
- django/conf/global_settings.py:35:1: unused-variable 'ALLOWED_HOSTS'
- django/conf/global_settings.py:41:1: unused-variable 'TIME_ZONE'
- django/conf/global_settings.py:44:1: unused-variable 'USE_TZ'
- django/conf/global_settings.py:50:1: unused-variable 'LANGUAGE_CODE'
- django/conf/global_settings.py:53:1: unused-variable 'LANGUAGES'
- django/conf/global_settings.py:157:1: unused-variable 'LANGUAGES_BIDI'
- django/conf/global_settings.py:161:1: unused-variable 'USE_I18N'
- django/conf/global_settings.py:162:1: unused-variable 'LOCALE_PATHS'
- django/conf/global_settings.py:165:1: unused-variable 'LANGUAGE_COOKIE_NAME'
- django/conf/global_settings.py:166:1: unused-variable 'LANGUAGE_COOKIE_AGE'
- django/conf/global_settings.py:167:1: unused-variable 'LANGUAGE_COOKIE_DOMAIN'
- django/conf/global_settings.py:168:1: unused-variable 'LANGUAGE_COOKIE_PATH'
- django/conf/global_settings.py:169:1: unused-variable 'LANGUAGE_COOKIE_SECURE'
- django/conf/global_settings.py:170:1: unused-variable 'LANGUAGE_COOKIE_HTTPONLY'
- django/conf/global_settings.py:171:1: unused-variable 'LANGUAGE_COOKIE_SAMESITE'
- django/conf/global_settings.py:179:1: unused-variable 'DEFAULT_CHARSET'
- django/conf/global_settings.py:182:1: unused-variable 'SERVER_EMAIL'
- django/conf/global_settings.py:185:1: unused-variable 'DATABASES'
- django/conf/global_settings.py:188:1: unused-variable 'DATABASE_ROUTERS'
- django/conf/global_settings.py:199:1: unused-variable 'EMAIL_BACKEND'
- django/conf/global_settings.py:203:1: unused-variable 'EMAIL_HOST'
- django/conf/global_settings.py:207:1: unused-variable 'EMAIL_PORT'
- django/conf/global_settings.py:210:1: unused-variable 'EMAIL_USE_LOCALTIME'
- django/conf/global_settings.py:214:1: unused-variable 'EMAIL_HOST_USER'
- django/conf/global_settings.py:215:1: unused-variable 'EMAIL_HOST_PASSWORD'
- django/conf/global_settings.py:216:1: unused-variable 'EMAIL_USE_TLS'
- django/conf/global_settings.py:217:1: unused-variable 'EMAIL_USE_SSL'
- django/conf/global_settings.py:218:1: unused-variable 'EMAIL_SSL_CERTFILE'
- django/conf/global_settings.py:219:1: unused-variable 'EMAIL_SSL_KEYFILE'
- django/conf/global_settings.py:220:1: unused-variable 'EMAIL_TIMEOUT'
- django/conf/global_settings.py:223:1: unused-variable 'INSTALLED_APPS'
- django/conf/global_settings.py:225:1: unused-variable 'TEMPLATES'
- django/conf/global_settings.py:228:1: unused-variable 'FORM_RENDERER'
- django/conf/global_settings.py:231:1: unused-variable 'USE_BLANK_CHOICE_DASH'
- django/conf/global_settings.py:235:1: unused-variable 'DEFAULT_FROM_EMAIL'
- django/conf/global_settings.py:239:1: unused-variable 'EMAIL_SUBJECT_PREFIX'
- django/conf/global_settings.py:242:1: unused-variable 'APPEND_SLASH'
- django/conf/global_settings.py:245:1: unused-variable 'PREPEND_WWW'
- django/conf/global_settings.py:248:1: unused-variable 'FORCE_SCRIPT_NAME'
- django/conf/global_settings.py:260:1: unused-variable 'DISALLOWED_USER_AGENTS'
- django/conf/global_settings.py:262:1: unused-variable 'ABSOLUTE_URL_OVERRIDES'
- django/conf/global_settings.py:274:1: unused-variable 'IGNORABLE_404_URLS'
- django/conf/global_settings.py:279:1: unused-variable 'SECRET_KEY'
- django/conf/global_settings.py:283:1: unused-variable 'SECRET_KEY_FALLBACKS'
- django/conf/global_settings.py:285:1: unused-variable 'STORAGES'
- django/conf/global_settings.py:296:1: unused-variable 'MEDIA_ROOT'
- django/conf/global_settings.py:300:1: unused-variable 'MEDIA_URL'
... and 195 more
prefect: +0 -6
- src/integrations/prefect-redis/prefect_redis/messaging.py:723:11: unused-function 'ephemeral_subscription'
- src/integrations/prefect-redis/prefect_redis/messaging.py:755:11: unused-function 'break_topic'
- src/prefect/server/events/stream.py:27:1: unused-variable 'logger'
- src/prefect/server/utilities/messaging/memory.py:241:11: unused-function 'break_topic'
- src/prefect/server/utilities/messaging/memory.py:301:7: unused-class 'Publisher'
- src/prefect/server/utilities/messaging/memory.py:387:11: unused-function 'ephemeral_subscription'
rich: +0 -21
- rich/_unicode_data/unicode10-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode11-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode12-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode12-1-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode13-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode14-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode15-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode15-1-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode16-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode17-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode4-1-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode5-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode5-1-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode5-2-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode6-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode6-1-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode6-2-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode6-3-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode7-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode8-0-0.py:6:1: unused-variable 'cell_table'
- rich/_unicode_data/unicode9-0-0.py:6:1: unused-variable 'cell_table'
sphinx: +104 -81
- doc/development/tutorials/examples/autodoc_intenum.py:57:5: unused-function 'setup'
+ doc/development/tutorials/examples/helloworld.py:21:5: unused-attribute 'required_arguments'
- doc/development/tutorials/examples/helloworld.py:28:5: unused-function 'setup'
- doc/development/tutorials/examples/recipe.py:174:5: unused-function 'setup'
+ doc/development/tutorials/examples/todo.py:33:5: unused-attribute 'has_content'
- doc/development/tutorials/examples/todo.py:120:5: unused-function 'setup'
- sphinx/addnodes.py:575:5: unused-function 'setup'
+ sphinx/builders/changes.py:175:9: unused-method 'hl'
- sphinx/builders/changes.py:192:5: unused-function 'setup'
- sphinx/builders/dirhtml.py:41:5: unused-function 'setup'
- sphinx/builders/dummy.py:39:5: unused-function 'setup'
- sphinx/builders/epub3.py:288:5: unused-function 'setup'
- sphinx/builders/gettext.py:332:5: unused-function 'setup'
- sphinx/builders/html/__init__.py:1454:5: unused-function 'setup'
- sphinx/builders/latex/__init__.py:590:5: unused-function 'setup'
- sphinx/builders/latex/transforms.py:645:5: unused-function 'setup'
- sphinx/builders/linkcheck.py:807:5: unused-function 'setup'
- sphinx/builders/manpage.py:124:5: unused-function 'setup'
+ sphinx/builders/singlehtml.py:54:9: unused-method 'fix_refuris'
- sphinx/builders/singlehtml.py:208:5: unused-function 'setup'
- sphinx/builders/texinfo.py:239:5: unused-function 'setup'
- sphinx/builders/text.py:77:5: unused-function 'setup'
- sphinx/builders/xml.py:111:5: unused-function 'setup'
- sphinx/config.py:899:5: unused-function 'setup'
+ sphinx/directives/__init__.py:320:5: unused-attribute 'optional_arguments'
+ sphinx/directives/__init__.py:321:5: unused-attribute 'final_argument_whitespace'
+ sphinx/directives/__init__.py:356:5: unused-attribute 'has_content'
+ sphinx/directives/__init__.py:357:5: unused-attribute 'required_arguments'
+ sphinx/directives/__init__.py:358:5: unused-attribute 'optional_arguments'
+ sphinx/directives/__init__.py:359:5: unused-attribute 'final_argument_whitespace'
- sphinx/directives/__init__.py:369:5: unused-function 'setup'
+ sphinx/directives/admonitions.py:44:5: unused-attribute 'required_arguments'
+ sphinx/directives/admonitions.py:45:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:49:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:53:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:57:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:61:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:65:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:69:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:73:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:77:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:81:5: unused-attribute 'node_class'
+ sphinx/directives/admonitions.py:87:5: unused-attribute 'node_class'
- sphinx/directives/admonitions.py:90:5: unused-function 'setup'
+ sphinx/directives/code.py:37:5: unused-attribute 'has_content'
+ sphinx/directives/code.py:38:5: unused-attribute 'required_arguments'
+ sphinx/directives/code.py:39:5: unused-attribute 'optional_arguments'
+ sphinx/directives/code.py:40:5: unused-attribute 'final_argument_whitespace'
+ sphinx/directives/code.py:104:5: unused-attribute 'has_content'
+ sphinx/directives/code.py:105:5: unused-attribute 'required_arguments'
... and 135 more
sqlalchemy: +0 -6
- lib/sqlalchemy/dialects/mysql/base.py:1199:1: unused-variable 'MSTime'
- lib/sqlalchemy/dialects/mysql/base.py:1200:1: unused-variable 'MSSet'
- lib/sqlalchemy/dialects/mysql/base.py:1201:1: unused-variable 'MSEnum'
- lib/sqlalchemy/sql/default_comparator.py:431:1: unused-variable 'operator_lookup'
- lib/sqlalchemy/sql/dml.py:107:9: unused-function 'isdelete'
- lib/sqlalchemy/sql/dml.py:113:5: unused-variable 'isdelete'
strawberry: +0 -1
- strawberry/pydantic/fields.py:470:5: unused-function 'validate_field_type'
werkzeug: +0 -6
- examples/coolmagic/helpers.py:4:1: unused-variable 'request'
- tests/live_apps/data_app.py:8:5: unused-function 'app'
- tests/live_apps/reloader_app.py:18:5: unused-function 'app'
- tests/live_apps/reloader_app.py:24:1: unused-variable 'kwargs'
- tests/live_apps/standard_app.py:8:5: unused-function 'app'
- tests/live_apps/streaming_app.py:6:5: unused-function 'app'
zulip: +0 -9
- zerver/webhooks/bitbucketdatacenter/view.py:60:5: unused-function 'fixture_to_headers'
- zerver/webhooks/gitea/view.py:15:1: unused-variable 'fixture_to_headers'
- zerver/webhooks/github/view.py:44:1: unused-variable 'fixture_to_headers'
- zerver/webhooks/gitlab/view.py:52:5: unused-function 'fixture_to_headers'
- zerver/webhooks/gogs/view.py:31:1: unused-variable 'fixture_to_headers'
- zerver/webhooks/groove/view.py:126:1: unused-variable 'fixture_to_headers'
- zerver/webhooks/netlify/view.py:23:1: unused-variable 'fixture_to_headers'
- zerver/webhooks/patreon/view.py:25:1: unused-variable 'fixture_to_headers'
- zerver/webhooks/reviewboard/view.py:56:1: unused-variable 'fixture_to_headers'

@Apakottur Apakottur changed the title Count the names of a module reached as an object: imported by a string, or passed on Count the names of modules imported by a string or passed as a value as used Nov 22, 2026
@Apakottur
Apakottur merged commit f8f919b into main Nov 22, 2026
8 checks passed
@Apakottur
Apakottur deleted the modules-reached-dynamically branch November 22, 2026 11:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant