Skip to content

Add transforms to remove unused imports, variables, definitions and unreachable code - #156

Open
SahilRajputdotexe wants to merge 1 commit into
dflook:mainfrom
SahilRajputdotexe:feat/remove-dead-code
Open

SahilRajputdotexe wants to merge 1 commit into
dflook:mainfrom
SahilRajputdotexe:feat/remove-dead-code

Conversation

@SahilRajputdotexe

Copy link
Copy Markdown

This adds four opt-in transforms that remove dead code:

  • remove_unused_imports (--remove-unused-imports): drops imported names that are never used
  • remove_unused_variables (--remove-unused-variables): drops x = value when x is never used and the value has no side effects
  • remove_unused_definitions (--remove-unused-definitions): drops functions and classes that are never used
  • remove_unreachable (--remove-unreachable): drops statements after a return, raise, break or continue

They are off by default, because they can break code that is imported by something else or that relies on import side effects. Modules that use exec, eval, locals, globals, vars or a star import are left alone, and so are names in a literal __all__, dunder names, decorated definitions and class bodies.

Removing code can leave more unused, so the transforms repeat until nothing changes. For example, removing an unused helper() also removes the import json that only it used.

Unreachable code is only removed if that doesn't change how names resolve. A return followed by a yield stays, and so does a trailing assignment to a name that is read earlier in the function. A with body that only ends by raising doesn't count, because the context manager can swallow the exception.

There is a docs page for each option, a changelog entry and the stub arguments. The new tests pass on 3.8, 3.9, 3.11, 3.12 and 3.14 locally along with the existing suite, and I ran all four options over the standard library to check the output still compiles. The 2.7 and 3.3+ jobs run on CI.

…nreachable code

Each is an option that is disabled by default. They are repeated until no more code is removed, as removing code can leave other code unused.

This branch has not been deployed

No deployments
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