Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

My Framework Said Any: How a Pyrefly Error Led Me to Fix Typing in SwiftPY

I build SwiftPY, a Python web framework with an async Active Record ORM. Last week I opened one of my own repositories in VS Code and saw this: class DocRepository: model = Doc async def get_doc(self, doc_id:

I build SwiftPY, a Python web framework with an async Active Record ORM. Last week I opened one of my own repositories in VS Code and saw this:

class DocRepository:
    model = Doc

    async def get_doc(self, doc_id: int) -> Doc:
        doc = await self.model.where("is_active", True).with_("group").where("id", doc_id).first()
        if not doc:
            raise NotFoundError("Doc not found")
        return doc
Returning implicit Any from function declared to return "Doc"
Pyrefly[no-any-return-implicit]
(variable) doc: Unknown

Every method in the file was red. The code ran fine and the tests passed, yet the editor insisted my framework was returning Any. For a framework whose pitch includes being typed, that is the kind of bug you cannot ignore.

Reading the error properly

The most important line was easy to skip: doc: Unknown.

In Pyrefly, no-any-return-implicit does not mean you wrote Any somewhere. It means a type was lost along the way. So the real question was where the type disappeared, and I found two separate answers.

Cause 1: the type chain had gaps

A query like Doc.where(...).with_(...).order_by(...).get() is a chain of method calls. If any link in that chain has no return annotation, the checker gives up and everything after it becomes Unknown. Relationship queries, which are awaited through __await__, had the same problem.

SwiftPY 0.3.8 fixes this at the source. The concrete model type now flows through the whole chain: ModelQueryBuilder[T], RelationshipQueryBuilder[T] and SingleRelationshipQueryBuilder[T] all carry it, with annotated awaiting such as __await__() -> Generator[Any, None, list[T]] for collections and ... -> T | None for single results.

For you, as an application developer, none of that machinery is visible. This is all your repository needs:

from __future__ import annotations

from app.models.doc import Doc
from swiftpy import NotFoundError


class DocRepository:
    model = Doc

    async def get_doc(self, doc_id: int) -> Doc:
        doc = await self.model.where("is_active", True).with_("group").where("id", doc_id).first()
        if doc is None:
            raise NotFoundError("Doc not found")
        return doc  # inferred as Doc, no cast and no annotation needed

    async def get_docs(self) -> list[Doc]:
        return await self.model.where("is_active", True).order_by("sort_order").get()

No Generic, no TypeVar, no Self, and no model: type[Doc] boilerplate. The model = Doc line is the only declaration, and the types flow from it.

Cause 2: a global setting that hid the real problem

This one surprised me. Even with correct framework types, I could still get Unknown if my IDE's Python interpreter did not have swiftpy-framework installed. That happens constantly in Docker based workflows, where the packages live in a container and the editor's interpreter is empty.

When the editor cannot import swiftpy, Model becomes Unknown. Then every repository method returns Unknown, and the checker reports no-any-return-implicit on code that is perfectly fine. The error points at the symptom, not the cause.

The reason it stayed silent was a setting that my own swiftpy new scaffold generated:

[tool.mypy]
ignore_missing_imports = true
follow_imports = "silent"

Pyrefly reads [tool.mypy] when no pyrefly.toml exists. So this global switch told it to treat missing imports as fine and move on. A missing dependency turned into Unknown, and the Unknown turned into confusing errors somewhere else entirely.

The fix in 0.3.9: fail loudly

The scaffold now scopes the ignore to the specific libraries that really lack type information, using per package overrides instead of a global switch:

[[tool.mypy.overrides]]
module = ["asyncpg.*", "aiosmtplib.*", "jinja2.*"]
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = ["redis.*"]
disallow_untyped_calls = false

The result is the behaviour I wanted in the first place. If your editor's interpreter lacks SwiftPY, Pyrefly now says so directly:

[missing-import] Could not find import of `swiftpy`

That is a one line fix, instead of a rabbit hole. If your project works in Docker, install the framework into the interpreter your editor uses:

python -m pip install -U swiftpy-framework

No .venv is required for this. It only needs to exist where the editor looks.

Making metadata typecheck cleanly

Models declare behaviour through class attributes such as __fillable__, __guarded__ and __hidden__. Ruff's RUF012 rule wants mutable class attributes annotated with ClassVar, which would force boilerplate onto every model. The scaffold now ignores that rule where it does not help:

[tool.ruff.lint.per-file-ignores]
"app/models/**/*.py" = ["RUF012"]
"app/**/models/**/*.py" = ["RUF012"]
"tests/**/*.py" = ["RUF012"]

That covers standard layouts, feature grouped layouts and test models.

Typing is behaviour, so test it

The part I am most glad about is not the fix itself. It is that this class of bug now fails CI. Three layers guard it:

1. Type assertions. Tests use typing.assert_type on query chains, repository methods and relationships (HasMany, BelongsTo), and they are checked by both mypy --strict and Pyrefly:

from typing import assert_type

from app.models.doc import Doc


async def check_chain_types() -> None:
    assert_type(await Doc.where("id", 1).first(), Doc | None)
    assert_type(await Doc.with_("group").get(), list[Doc])

2. The built wheel. Shipping py.typed in the source tree proves nothing if the marker does not reach the published package. A test now checks that swiftpy/py.typed exists on disk, is listed in the Hatchling wheel config, and is inside the actual built .whl.

3. CI. GitHub Actions runs Pyrefly, then installs the built wheel in an isolated environment and smoke tests a freshly generated swiftpy new project.

For reference, the checks behind 0.3.9 came back clean:

  • ruff check . passed
  • mypy passed on the framework and on the whole repository (474 source files)
  • pyrefly check --error=no-any-return-implicit reported 0 errors (5 warnings) across the database layer, the app and the typing tests
  • uv build produced the sdist and wheel, and twine check passed on both
  • the targeted typing and scaffolding tests passed (27)

What I've learnt in all these so far

  1. Failing loudly is better than failing quietly. A global "ignore missing imports" switch feels convenient until it converts a missing dependency into a mystery elsewhere. Scope your ignores to the libraries that need them.
  2. Types should flow from one declaration. If users must write generics or casts to get a typed repository, the framework has pushed its work onto them.
  3. Test your types like you test your behaviour. assert_type costs almost nothing and catches regressions no unit test would.
  4. Verify the artifact, not the source tree. Packaging bugs only show up in the built wheel.

Help me test this in your editor

SwiftPY is still in beta, and typing is a place where the diversity of your setups matters. Editors, interpreters, Docker layouts and type checkers all behave differently, and I only have mine.

If you use Pyrefly, mypy or Pyright, I would love to know whether your repositories come out clean. The Pyright side is designed to work the same way, but my CI verifies mypy and Pyrefly, so confirmation from Pyright users would help a lot.

  • Try a fresh project: swiftpy new my_service
  • Open a repository in your editor and see what the checker infers
  • Report any Unknown or Any that appears: https://github.com/Obrainwave/swiftpy

You can also send me a DM with "SWIFTPY TESTER" and I will help you get started.

SwiftPY: Building towards 1.0.0.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.