DJRHails / PyMender

Perform entire codebase refactors in a way that is reproducible, testable and reviewable. Convert to FastAPI Annotated in one step.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

👷‍♀️ PyMender

Perform entire codebase refactors in a way that is reproducible, testable and reviewable. Obeys .gitignore by default.

Usage

pip install pymender==0.2.0

pymender <codemod> <path_to_project>

What codemods are available?

FastAPIAnnotated

Converts FastAPI endpoints to use the preferred Annotated[<type>, Depends(<dependency>)] syntax rather than : <type> = Depends(<dependency>).

Why?

  • Default value of the function parameter is the actual default value.
  • Reuse of the function is now possible.
  • Type-safe usage of the functions, previously 'default' values where not type checked.
  • Multi-purpose e.g. Annotated[str, fastapi.Query(), typer.Argument()] is now possible.
pymender FastAPIAnnotated <folder-to-upgrade>
Before After
@router.get('/example')
def example_function(
value: int,
query: str = Query("foo"),
zar: str = Query(default="bar", alias="z"),
foo: str = Depends(get_foo),
*,
bar: str = Depends(get_bar),
body: str = Body(...),
) -> str:
return 'example'
@router.get('/example')
def example_function(
value: int,
foo: Annotated[str, Depends(get_foo)],
query: Annotated[str, Query()] = "foo",
zar: Annotated[str, Query(alias="z")] = "bar",
*,
bar: Annotated[str, Depends(get_bar)],
body: Annotated[str, Body()],
) -> str:
return 'example'

Developer Guide

# Run a particular codemod
python3 -m pymender <codemod> <path_to_project>
# e.g.
python3 -m pymender FastAPIAnnotated <path_to_project>

# Run the codemod directly
python3 -m libcst.tool codemode fastapi_annotated.FastAPIAnnotated <path_to_project>

# Run tests
pytest -vv

Thanks to:

  • libCST which does a lot of the hardwork for this.
  • autotyping for showing what was possible.

About

Perform entire codebase refactors in a way that is reproducible, testable and reviewable. Convert to FastAPI Annotated in one step.


Languages

Language:Python 100.0%