Starter Brains · Python

Python Backend & APIs

20 lessons from merged PRs in FastAPI, Pydantic and Flask, summarized in our own words. The classic Python typing, serialization and ASGI traps.

20 PR lessonsfastapi/fastapi · MIT (3)pydantic/pydantic · MIT (9)pallets/flask · BSD-3-Clause (8)
brain_seed_starter(instance_id="<your-brain-id>", stack="python")

20 fixes from merged PRs

Every lesson below is a short summary in our own words and links to its upstream GitHub pull request in a permissive-licensed repository. Seed them into your Brain so your coding agent can find them when a similar problem comes up.

  1. fastapi:pr-10240MITfastapi/fastapi#10240 ↗
    Symptom

    Type checkers complain about the endpoint argument of FastAPI.add_api_route because its annotation differs from the one used by related routing calls.

    Cause and fix

    Cause: The endpoint parameter in FastAPI.add_api_route had a narrower type than the downstream APIRouter.add_api_route, get_typed_return_annotation and Starlette's Route, which accept Callable[..., Any]. Fix: The endpoint parameter annotation in applications.py was changed to Callable[..., Any] to match those downstream calls.

  2. fastapi:pr-538MITfastapi/fastapi#538 ↗
    Symptom

    Including an APIRouter that uses a custom route_class into another router loses that class, so the parent router's class is applied to the included routes.

    Cause and fix

    Cause: include_router rebuilt every included route with the parent router's route_class instead of retaining each route's own class. Fix: include_router in routing.py now keeps the existing class of routes that are APIRoute subclasses when copying them into the parent router; a custom route class test covers it.

  3. fastapi:pr-437MITfastapi/fastapi#437 ↗
    Symptom

    FastAPI's generated OpenAPI 422 response ignores a custom response_class media type and overwrites a customized validation-error format with the default one.

    Cause and fix

    Cause: The OpenAPI generator always inserted a hard-coded default 422 definition and did not take the media type from the route's response class for additional responses. Fix: openapi/utils.py now uses a user-supplied 422 response definition when one exists and falls back to the default only otherwise, and it takes the media type of response_class for additional responses.

  4. pydantic:pr-13087MITpydantic/pydantic#13087 ↗
    Symptom

    Calling model_copy(deep=True, update={...}) in Pydantic wastes time and can crash on fields that cannot be deep-copied, even though update replaces those fields anyway.

    Cause and fix

    Cause: The implementation deep-copied the whole model first and applied the update dict afterwards, so fields about to be overwritten were copied and then thrown away. Fix: Fields present in update are no longer deep-copied; the remaining fields are copied with one shared memo dict to keep shared references, and extra and private state are handled as before.

  5. pydantic:pr-12680MITpydantic/pydantic#12680 ↗
    Symptom

    Using a RootModel[Literal[...]] as a discriminator field in a Pydantic discriminated union raises PydanticUserError saying the field must be of type Literal.

    Cause and fix

    Cause: Discriminator value inference did not look inside a root model, so a model schema flagged as root_model was not recognized as a Literal. Fix: _infer_discriminator_values_for_inner_schema now handles a 'model' schema with the root_model flag by unwrapping it to the inner Literal schema, with tests for single and multiple values.

  6. pydantic:pr-12879MITpydantic/pydantic#12879 ↗
    Symptom

    mypy reports errors when a class built with pydantic's create_model() is used in a type annotation, isinstance check or function parameter, forcing type: ignore comments.

    Cause and fix

    Cause: The pydantic mypy plugin had no handling for dynamically created classes, so variables assigned from create_model() were not treated as class types. Fix: A get_dynamic_class_hook was added to the mypy plugin so create_model() results become proper class types, including inheriting from the class given in the __base__ keyword.

  7. pydantic:pr-12494MITpydantic/pydantic#12494 ↗
    Symptom

    Pydantic JSON schema generation emits duplicate definitions such as Schema-Input and Schema-Output for deeply nested models whose input and output schemas are identical.

    Cause and fix

    Cause: In _DefinitionsRemapping.from_prioritized_choices the json_remapping dict mapped only the original key to the final key, not the intermediate simplified names, so identical schemas were not merged. Fix: The remapping now also records the intermediate simplified names, letting identical input and output schemas collapse into one definition.

  8. pydantic:pr-12741MITpydantic/pydantic#12741 ↗
    Symptom

    A Pydantic dataclass decorated with kw_only=True shows a wrong constructor signature when a field uses Field(kw_only=False), although positional passing still works.

    Cause and fix

    Cause: The dataclass conversion did not let a per-field Field(kw_only=False) override the class-level kw_only setting when building the signature. Fix: The dataclass handling was updated so Field(kw_only=...) on a single field overrides the decorator's kw_only parameter, with unit tests confirming the resulting signature.

  9. pydantic:pr-12760MITpydantic/pydantic#12760 ↗
    Symptom

    Pydantic generates a JSON schema whose default list changes order between runs when a field default is a set or frozenset, breaking reproducible builds.

    Cause and fix

    Cause: Python hash randomization makes set iteration order vary between processes, and the values were encoded into the schema in that order. Fix: GenerateJsonSchema.default_schema now sorts set and frozenset values before encoding them, so the default list is stable across runs.

  10. pydantic:pr-12846MITpydantic/pydantic#12846 ↗
    Symptom

    Pyright reports no matching overload when passing Pydantic's own Annotated aliases like NewPath or FilePath to validate_as in the experimental pipeline, although it works at runtime.

    Cause and fix

    Cause: The validate_as overloads only accepted type[T] or an ellipsis, while these aliases are _AnnotatedAlias objects that do not match type[T]. Fix: An overload taking Any was added as a last fallback, after type[_NewOutT] and EllipsisType, returning _Pipeline[_InT, Any] for Annotated aliases and similar type expressions.

  11. pydantic:pr-13452MITpydantic/pydantic#13452 ↗
    Symptom

    In Pydantic's experimental pipeline, an annotated_types.Interval with a bound of 0 is silently ignored, so Interval(ge=0, le=10) accepts -5.

    Cause and fix

    Cause: _apply_constraint in pipeline.py tested each Interval bound for truthiness, and 0 is falsy, so zero bounds were skipped. Fix: The four checks for ge, gt, le and lt now use 'is not None', and test_interval_constraints gained cases with a zero bound for each.

  12. pydantic:pr-11759MITpydantic/pydantic#11759 ↗
    Symptom

    Calling model_rebuild on a Pydantic subclass whose parent has an unresolved forward reference to it does nothing, because the subclass is wrongly treated as already complete.

    Cause and fix

    Cause: ModelMetaclass.__new__ marked a subclass as complete without verifying that its fields were resolved, unlike model_rebuild, so subclasses of incomplete parents got flagged complete. Fix: The metaclass now performs the same field-completeness check, rebuilding fields to look for unresolved annotations, before marking a new model class as complete.

  13. flask:pr-4461BSD-3-Clausepallets/flask#4461 ↗
    Symptom

    click.get_current_context() returns None inside a Flask app factory when running the flask command with the reloader.

    Cause and fix

    Cause: With lazy loading, the default under the reloader, the app factory runs in a separate thread, and Click's context is thread-local. Fix: In cli.py the lazily loaded app is now created so the Click context stays available consistently inside the flask command.

  14. flask:pr-5799BSD-3-Clausepallets/flask#5799 ↗
    Symptom

    Using stream_with_context in an async Flask view fails, while the same route written as a sync function works.

    Cause and fix

    Cause: The request context created and pushed its own app context, then popped it automatically, and the internal ContextVar became tied to the temporary event loop used by async views. Fix: In helpers.py the generator now stores the app context along with the request context, and both are pushed (app context first) only when iteration begins rather than during setup.

  15. flask:pr-4642BSD-3-Clausepallets/flask#4642 ↗
    Symptom

    A FlaskGroup nested inside a larger click group ignores the create_app factory passed to it and loses other Flask CLI behavior.

    Cause and fix

    Cause: FlaskGroup put its custom setup in main(), which Click does not call when a nested group's subcommands are invoked. Fix: The custom behavior was moved from FlaskGroup.main into __init__ and make_context, so both flask.cli.cli and custom FlaskGroup instances work when nested under another CLI.

  16. flask:pr-3182BSD-3-Clausepallets/flask#3182 ↗
    Symptom

    Flask fails to serve static files when static_url_path ends with a slash, for example /foo/ or /.

    Cause and fix

    Cause: The static route appends a rule that already starts with a slash, so a prefix ending in a slash produced a doubled slash. Fix: The static URL path handling in app.py and blueprints.py was changed so a trailing slash on static_url_path no longer breaks the route, with a new test in test_basic.py.

  17. flask:pr-3434BSD-3-Clausepallets/flask#3434 ↗
    Symptom

    With the reloader active, flask run hides startup syntax errors until the first request because the app is imported lazily.

    Cause and fix

    Cause: Lazy loading was the default whenever the reloader was enabled, including on the very first load. Fix: When neither --eager-loading nor --lazy-loader is given, flask run now loads eagerly on first start so errors show immediately, then loads lazily on reloads so the server stays up.

  18. flask:pr-3435BSD-3-Clausepallets/flask#3435 ↗
    Symptom

    Flask send_file with an io.StringIO object returns 200 OK with an empty body and prints a traceback in the terminal.

    Cause and fix

    Cause: send_file only works with binary data, and a text-mode file object cannot be streamed correctly. Fix: send_file in helpers.py now raises ValueError when given an io.TextIOBase instance, so the mistake is reported instead of yielding a blank file.

  19. flask:pr-4074BSD-3-Clausepallets/flask#4074 ↗
    Symptom

    Flask cannot nest the same blueprint in different places, and url_for fails when one blueprint is registered under several prefixes, because registration uses only the blueprint's own name.

    Cause and fix

    Cause: Blueprints were registered under the name they were created with, not the full dotted name that includes their parent. Fix: Blueprints are now registered under their full nested name, and register_blueprint accepts a name option that changes the registered name.

  20. flask:pr-4603BSD-3-Clausepallets/flask#4603 ↗
    Symptom

    mypy reports a type error for an after_request function annotated with Flask's own Response, which type-checked fine in Flask 2.0.

    Cause and fix

    Cause: AfterRequestCallable was typed to take Werkzeug's base Response, but Flask passes its Response subclass to callbacks. Fix: typing.py introduces a ResponseType type variable bound to Werkzeug's Response and uses it in AfterRequestCallable, with the decorators in app, blueprints, scaffold, ctx and views updated to match.

Explain it once. Every AI knows it. By default, no generative AI model reads or rewrites your lessons. A small ranking model in the EU only scores them. Starter lessons never overwrite your team's own project lessons.