Repository navigation
Count the names of modules imported by a string or passed as a value as used - #284
Merged
Merged
Conversation
…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
Contributor
PerformanceTime to check CPython v3.15.0: the median of 15 runs of each binary, run in turns.
EcosystemFindings 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 moreprefect: +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 moresqlalchemy: +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' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
A module-level function, class or variable counted as used only when it was read in its module, imported, read as
module.namethrough an imported name, listed in__all__, or looked up inglobals(). When a module was reached as an object some other way (byimportlib.import_module, or passed as an argument), all its names were reported. Matching everyvalue.nameread 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.nameread keeps every module-levelname). I ran it and main (b785eca) with--show-transitiveon the 19 projects ofscripts/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.
import_module("pkg.mod")/__import__import_module("ansible_test._internal")then.main()f"pkg.{x}","pkg.%s" % x,f"{pkg.__name__}.x.{y}")tests/live_apps/run.py:import_module(f"{name}_app").app; ansible_ansiballz/_loader.py:import_module(f'{_ansiballz.__name__}._extensions.{x}').runsetup), rich 21, zulip 9, prefect 5include():getattr(import_module(urlconf), "urlpatterns")(110 test urlconfs); sphinxregistry.py:getattr(import_module(extname), "setup"); prefectimport_module(BROKER.value()).Publisher; richimport_module(name, "rich._unicode_data").cell_tablefor s in dir(global_settings): setattr(self, s, getattr(global_settings, s)), read assettings.X; ansiblefrom ...distro import _distro as distro,distro = _system_distro or _distro; strawberryintegration = fields; integration.validate_field_type(...); sqlalchemyutil.preloaded:sql_traversals = _sql_traversalssys.modules[...]plugin_baseby path intosys.modules["sqla_plugin_base"](counted in (g))upgrade,downgrade,revision...); ansibleDOCUMENTATION296 (read by path / AST); DjangoCommandin zulip 101 (on main since #283); sphinxconf.pyvalues 89; settings modules 28tests/data624 (formatter inputs:f,x,foo); the rest are names likelogger,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
Literal string → exact module.
m = import_module("pkg.mod"),__import__("pkg.mod", fromlist=...)and__import__("pkg.mod")(the top package) bindmasimport ... as mwould. Relative strings withpackage=__package__/__name__or a literal package work too. The attributes stay loose reads as well: the module can be replaced insys.modules, as openlibrary's tests do. Without that, two test stubs became new findings.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, andpkg.__name__as the namepkgwas imported as. A name with no literal part matches any module. This rule covers (b) and (c). It is tracked likelocal_calls: a name assigned the call in the same scope.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.nameread. That is how attributes of objects are matched already, and likelooseinclass_members.rs. It does not count as passed when:setattr/monkeypatch.setattr,patch.object,reload,isinstance,getattrorhasattr(without this, openlibrary lost 18 findings, all coincidental);from .directive import directivedoes (strawberry's@strawberry.directive(...)madestrawberry/directive.pyescape).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:
urlpatterns+ 132global_settingsvalues + 3 modules loaded by test strings (SessionStore...); sphinx 81 extensionsetupfunctions (+297 they reach); rich 21cell_table; zulip 9fixture_to_headers; prefect brokerPublisher/ephemeral_subscription/break_topic; werkzeug live appsapp/kwargs; ansible ansiballz extensions,distro, ansible-testmain; sqlalchemy 13 MySQL type aliases (m = mysql; m.MSYearin tests), thepreloadednamesoperator_lookupand_get_children, the mssqlpythondialect, anddml.isupdate/isdelete(called fromsql/crud.py); strawberry's pydantic integration; pelican's dummy pluginregister.server/events/stream.pylogger(the module sits in a list of services, and.loggeris read elsewhere; the test patches a different module,logs/stream.py); sqlalchemytesting/config.pytest_schema_2(assigned throughglobal, only read ascfg.test_schema_2on a Config object); sqlalchemyorm/attributes.pyhas_parent/init_collection(only called from tests that unref does not reach;.has_parentread 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 81setupfunctions, 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 deadappin a werkzeug example, andf"{pkg.__name__}..."kept 5runfunctions in ansible'spackaging/release.py. Rule 2's real cost is for a name with no literal part:module.setupthen keeps every module-levelsetupin 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 compareagainst the main release binary (CPython, median of 15):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
DOCUMENTATION, Sphinxconf.pyvalues, settings modules,sys.modules[...] = load_file(...). These belong in framework rules (Alembic would be a new one).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 thanpkg.*; this covers zulip's webhooks and rich's unicode tables). They could be added likelocal_callsif precision there matters.getattr(module, name)with a dynamic name, anddir(module). The module escapes, but only names read somewhere as attributes are kept.Verification
tests/cases/modules_as_objects: plugins by f-string, relative with__package__andf"{__name__}.{x}", an exact backend,"%s.handlers.%s", a fully dynamic extension,__import__withfromlist, a module passed to a function,setattr/isinstance/hasattrthat do not pass it, and a package whose name is rebound. Negative lines: the same names inunreached/plugin.py,apps/shop/views/orders.py(outside the glob),tools/parsing.py(never passed) andwidgets/button.pyare still reported.docs/rules.md: a new "Modules as objects" section.cargo test: passuv run pytest -c tests/pytest.ini tests: 288 passeduv run prek run -a: all pass