failed WRONG_FIX wrong_fix ยท 34 tool calls ยท 158 s ยท fastapi/fastapi
๐ Fix handling arbitrary types when using `arbitrary_types_allowed=True` ๐ Fix handling arbitrary types when using `arbitrary_types_allowed=True` Related to https://github.com/fastapi/fastapi/discussions/14184, https://github.com/fastapi/fastapi/issues/14483
| # | Tool | Arguments | Result |
|---|---|---|---|
| 1 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" ."
} | {"status": "ok", "stdout": "./tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_inherited_custom_class.pfull{"status": "ok", "stdout": "./tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_inherited_custom_class.py:89: arbitrary_types_allowed = True\n./tests/test_compat.py:87: model_config = ConfigDict(arbitrary_types_allowed=True)\n./tests/test_compat.py:92: arbitrary_types_allowed=True,\n./tests/test_jsonable_encoder.py:248: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:252: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:264: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:268: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:279: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:283: arbitrary_types_allowed = True\n", "exit_code": 0} |
| 2 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" fastapi | head -20"
} | {"status": "ok", "stdout": "", "exit_code": 0}full{"status": "ok", "stdout": "", "exit_code": 0} |
| 3 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" . | grep \"fastapi/\" | head -20"
} | {"status": "ok", "stdout": "", "exit_code": 0}full{"status": "ok", "stdout": "", "exit_code": 0} |
| 4 | run_command | {
"command": "find fastapi -name \"*.py\" | xargs grep -l \"arbitrary_types_allowed\" || echo \"not found\""
} | {"status": "ok", "stdout": "not found\n", "exit_code": 0}full{"status": "ok", "stdout": "not found\n", "exit_code": 0} |
| 5 | run_command | {
"command": "python3 -c \"\nfrom pydantic import BaseModel, ConfigDict\nclass Custom:\n pass\n\ntry:\n class Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n print('Pydantic Model created successfully')\nexcept Exception as e:\n print(f'Pydantic Model failed: {e}')\n\""
} | {"status": "ok", "stdout": "Pydantic Model created successfully\n", "exit_code": 0}full{"status": "ok", "stdout": "Pydantic Model created successfully\n", "exit_code": 0} |
| 6 | run_command | {
"command": "python3 -c \"\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, ConfigDict\nfrom fastapi.testclient import TestClient\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\napp = FastAPI()\n\n@app.post('/test')\nasync def test(item: Model):\n return item\n\nclient = TestClient(app)\ntry:\n # Pydantic V2 might fail to validate Custom from a dict if it doesn't know how\n # But we are testing if FastAPI handles the Model with arbitrary_types_allowed\n # Let's try to send a request that should be validated.\n # Actually, Pydantic will fail if we send JSON for a Custom type.\n # The issue might be related to how FastAPI handles these models.\n print('Sending request...')\n response = client.post('/test', json={'x': 'something'})\n print(f'Response: {response.status_code}, {response.json()}')\nexcept Exception as e:\n print(f'Error: {e}')\n\""
} | {"status": "ok", "stdout": "Sending request...\nResponse: 422, {'detail': [{'type': 'is_instance_of', 'loc': ['body', 'x'], 'msg': 'Input should be an instance full{"status": "ok", "stdout": "Sending request...\nResponse: 422, {'detail': [{'type': 'is_instance_of', 'loc': ['body', 'x'], 'msg': 'Input should be an instance of Custom', 'input': 'something', 'ctx': {'class': 'Custom'}}]}\n", "exit_code": 0} |
| 7 | run_command | {
"command": "python3 -c \"\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, ConfigDict\nfrom fastapi.testclient import TestClient\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\napp = FastAPI()\n\n@app.post('/test')\nasync def test(item: Model):\n return {'x': item.x}\n\nclient = TestClient(app)\n\n# Now create a real instance of Custom\ncustom_instance = Custom(123)\n# We can't send it as JSON. We need to see if FastAPI's internal handling of the model\n# causes issues when it's used in other ways, or if there is a specific crash.\n\n# Let's try to see if we can use it as a dependency or something.\n\""
} | {"status": "ok", "stdout": "", "exit_code": 0}full{"status": "ok", "stdout": "", "exit_code": 0} |
| 8 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" tests/test_inherited_custom_class.py"
} | {"status": "ok", "stdout": "45: model_config = {\"arbitrary_types_allowed\": True}\n89: arbitrary_types_allowed = True\n", "exit_code": 0}full{"status": "ok", "stdout": "45: model_config = {\"arbitrary_types_allowed\": True}\n89: arbitrary_types_allowed = True\n", "exit_code": 0} |
| 9 | read_file | {
"filepath": "tests/test_inherited_custom_class.py",
"start_line": 1,
"end_line": 100
} | {"status": "ok", "filepath": "tests/test_inherited_custom_class.py", "content": "import uuid\n\nimport pytest\nfrom fastapi import FastAPI\nfrom fastapi.testclifull{"status": "ok", "filepath": "tests/test_inherited_custom_class.py", "content": "import uuid\n\nimport pytest\nfrom fastapi import FastAPI\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\nfrom .utils import needs_pydanticv1, needs_pydanticv2\n\n\nclass MyUuid:\n def __init__(self, uuid_string: str):\n self.uuid = uuid_string\n\n def __str__(self):\n return self.uuid\n\n @property # type: ignore\n def __class__(self):\n return uuid.UUID\n\n @property\n def __dict__(self):\n \"\"\"Spoof a missing __dict__ by raising TypeError, this is how\n asyncpg.pgroto.pgproto.UUID behaves\"\"\"\n raise TypeError(\"vars() argument must have __dict__ attribute\")\n\n\n@needs_pydanticv2\ndef test_pydanticv2():\n from pydantic import field_serializer\n\n app = FastAPI()\n\n @app.get(\"/fast_uuid\")\n def return_fast_uuid():\n asyncpg_uuid = MyUuid(\"a10ff360-3b1e-4984-a26f-d3ab460bdb51\")\n assert isinstance(asyncpg_uuid, uuid.UUID)\n assert type(asyncpg_uuid) is not uuid.UUID\n with pytest.raises(TypeError):\n vars(asyncpg_uuid)\n return {\"fast_uuid\": asyncpg_uuid}\n\n class SomeCustomClass(BaseModel):\n model_config = {\"arbitrary_types_allowed\": True}\n\n a_uuid: MyUuid\n\n @field_serializer(\"a_uuid\")\n def serialize_a_uuid(self, v):\n return str(v)\n\n @app.get(\"/get_custom_class\")\n def return_some_user():\n # Test that the fix also works for custom pydantic classes\n return SomeCustomClass(a_uuid=MyUuid(\"b8799909-f914-42de-91bc-95c819218d01\"))\n\n client = TestClient(app)\n\n with client:\n response_simple = client.get(\"/fast_uuid\")\n response_pydantic = client.get(\"/get_custom_class\")\n\n assert response_simple.json() == {\n \"fast_uuid\": \"a10ff360-3b1e-4984-a26f-d3ab460bdb51\"\n }\n\n assert response_pydantic.json() == { |
| 10 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" . | grep \"fastapi/\""
} | {"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}}full{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}} |
| 11 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" ."
} | {"status": "ok", "stdout": "./tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_inherited_custom_class.pfull{"status": "ok", "stdout": "./tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_inherited_custom_class.py:89: arbitrary_types_allowed = True\n./tests/test_compat.py:87: model_config = ConfigDict(arbitrary_types_allowed=True)\n./tests/test_compat.py:92: arbitrary_types_allowed=True,\n./tests/test_jsonable_encoder.py:248: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:252: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:264: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:268: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:279: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:283: arbitrary_types_allowed = True\n", "exit_code": 0} |
| 12 | run_command | {
"command": "grep -rn \"jsonable_encoder\" fastapi | head -20"
} | {"status": "ok", "stdout": "fastapi/exception_handlers.py:1:from fastapi.encoders import jsonable_encoder\nfastapi/exception_handlers.py:25: content={\"detail\"full{"status": "ok", "stdout": "fastapi/exception_handlers.py:1:from fastapi.encoders import jsonable_encoder\nfastapi/exception_handlers.py:25: content={\"detail\": jsonable_encoder(exc.errors())},\nfastapi/exception_handlers.py:33: code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors())\nfastapi/routing.py:47:from fastapi.encoders import jsonable_encoder\nfastapi/routing.py:295: return jsonable_encoder(\nfastapi/routing.py:305: return jsonable_encoder(response_content)\nfastapi/encoders.py:114:def jsonable_encoder(\nfastapi/encoders.py:247: return jsonable_encoder(\nfastapi/encoders.py:258: return jsonable_encoder(\nfastapi/encoders.py:294: encoded_key = jsonable_encoder(\nfastapi/encoders.py:302: encoded_value = jsonable_encoder(\nfastapi/encoders.py:316: jsonable_encoder(\nfastapi/encoders.py:346: return jsonable_encoder(\nfastapi/openapi/docs.py:5:from fastapi.encoders import jsonable_encoder\nfastapi/openapi/docs.py:137: html += f\"{json.dumps(key)}: {json.dumps(jsonable_encoder(value))},\\n\"\nfastapi/openapi/docs.py:151: ui.initOAuth({json.dumps(jsonable_encoder(init_oauth))})\nfastapi/openapi/utils.py:23:from fastapi.encoders import jsonable_encoder\nfastapi/openapi/utils.py:85: security_definition = jsonable_encoder(\nfastapi/openapi/utils.py:168: parameter[\"examples\"] = jsonable_encoder(openapi_examples)\nfastapi/openapi/utils.py:170: parameter[\"example\"] = jsonable_encoder(example)\n", "exit_code": 0} |
| 13 | read_file | {
"end_line": 350,
"filepath": "fastapi/encoders.py",
"start_line": 110
} | {"status": "ok", "filepath": "fastapi/encoders.py", "content": "\nencoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)\n\n\ndef jsonabfull{"status": "ok", "filepath": "fastapi/encoders.py", "content": "\nencoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)\n\n\ndef jsonable_encoder(\n obj: Annotated[\n Any,\n Doc(\n \"\"\"\n The input object to convert to JSON.\n \"\"\"\n ),\n ],\n include: Annotated[\n Optional[IncEx],\n Doc(\n \"\"\"\n Pydantic's `include` parameter, passed to Pydantic models to set the\n fields to include.\n \"\"\"\n ),\n ] = None,\n exclude: Annotated[\n Optional[IncEx],\n Doc(\n \"\"\"\n Pydantic's `exclude` parameter, passed to Pydantic models to set the\n fields to exclude.\n \"\"\"\n ),\n ] = None,\n by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `by_alias` parameter, passed to Pydantic models to define if\n the output should use the alias names (when provided) or the Python\n attribute names. In an API, if you set an alias, it's probably because you\n want to use it in the result, so you probably want to leave this set to\n `True`.\n \"\"\"\n ),\n ] = True,\n exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_unset` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that were not explicitly\n set (and that only had their default values).\n \"\"\"\n ),\n ] = False,\n exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that had the same default\n value, even when they were explicitly set.\n \"\"\" |
| 14 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n encoded = jsonable_encoder(model)\n print(f'Encoded: {encoded}')\nexcept Exception as e:\n print(f'Error encoding: {e}')\n import traceback\n traceback.print_exc()\n\""
} | {"status": "ok", "stdout": "Error encoding: Unable to serialize unknown type: <class '__main__.Custom'>\n", "exit_code": 0}full{"status": "ok", "stdout": "Error encoding: Unable to serialize unknown type: <class '__main__.Custom'>\n", "exit_code": 0} |
| 15 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n # Let's see what happens when we call it on just the Custom instance\n encoded = jsonable_encoder(custom_instance)\n print(f'Encoded Custom: {encoded}')\nexcept Exception as e:\n print(f'Error encoding Custom: {e}')\n\""
} | {"status": "ok", "stdout": "Encoded Custom: {'val': 123}\n", "exit_code": 0}full{"status": "ok", "stdout": "Encoded Custom: {'val': 123}\n", "exit_code": 0} |
| 16 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n encoded = jsonable_encoder(model)\n print(f'Encoded: {encoded}')\nexcept Exception as e:\n print(f'Error: {e}')\n\""
} | {"status": "ok", "stdout": "Error: Unable to serialize unknown type: <class '__main__.Custom'>\n", "exit_code": 0}full{"status": "ok", "stdout": "Error: Unable to serialize unknown type: <class '__main__.Custom'>\n", "exit_code": 0} |
| 17 | read_file | {
"end_line": 356,
"filepath": "fastapi/encoders.py",
"start_line": 260
} | {"status": "ok", "filepath": "fastapi/encoders.py", "content": " include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclufull{"status": "ok", "filepath": "fastapi/encoders.py", "content": " include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_defaults=exclude_defaults,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if isinstance(obj, Enum):\n return obj.value\n if isinstance(obj, PurePath):\n return str(obj)\n if isinstance(obj, (str, int, float, type(None))):\n return obj\n if _is_undefined(obj):\n return None\n if isinstance(obj, dict):\n encoded_dict = {}\n allowed_keys = set(obj.keys())\n if include is not None:\n allowed_keys &= set(include)\n if exclude is not None:\n allowed_keys -= set(exclude)\n for key, value in obj.items():\n if (\n (\n not sqlalchemy_safe\n or (not isinstance(key, str))\n or (not key.startswith(\"_sa\"))\n )\n and (value is not None or not exclude_none)\n and key in allowed_keys\n ):\n encoded_key = jsonable_encoder(\n key,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n encoded_value = jsonable_encoder(\n value,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n encoded_dict[encoded_key] = encoded_value\n return encoded_d |
| 18 | read_file | {
"end_line": 235,
"filepath": "fastapi/encoders.py",
"start_line": 160
} | {"status": "ok", "filepath": "fastapi/encoders.py", "content": " \"\"\"\n ),\n ] = False,\n exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `efull{"status": "ok", "filepath": "fastapi/encoders.py", "content": " \"\"\"\n ),\n ] = False,\n exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that had the same default\n value, even when they were explicitly set.\n \"\"\"\n ),\n ] = False,\n exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_none` parameter, passed to Pydantic models to define\n if it should exclude from the output any fields that have a `None` value.\n \"\"\"\n ),\n ] = False,\n custom_encoder: Annotated[\n Optional[Dict[Any, Callable[[Any], Any]]],\n Doc(\n \"\"\"\n Pydantic's `custom_encoder` parameter, passed to Pydantic models to define\n a custom encoder.\n \"\"\"\n ),\n ] = None,\n sqlalchemy_safe: Annotated[\n bool,\n Doc(\n \"\"\"\n Exclude from the output any fields that start with the name `_sa`.\n\n This is mainly a hack for compatibility with SQLAlchemy objects, they\n store internal SQLAlchemy-specific state in attributes named with `_sa`,\n and those objects can't (and shouldn't be) serialized to JSON.\n \"\"\"\n ),\n ] = True,\n) -> Any:\n \"\"\"\n Convert any object to something that can be encoded in JSON.\n\n This is used internally by FastAPI to make sure anything you return can be\n encoded as JSON before it is sent to the client.\n\n You can also use it yourself, for example to convert objects before saving them\n in a database that supports only JSON.\n\n Read more about it in the\n [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/). |
| 19 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n encoded = jsonable_encoder(model)\n print(f'Encoded: {encoded}')\nexcept Exception as e:\n print(f'Error: {e}')\n\""
} | {"status": "ok", "stdout": "Error: Unable to serialize unknown type: <class '__main__.Custom'>\n", "exit_code": 0}full{"status": "ok", "stdout": "Error: Unable to serialize unknown type: <class '__main__.Custom'>\n", "exit_code": 0} |
| 20 | run_command | {
"command": "grep -rn \"Unable to serialize unknown type\" fastapi/encoders.py"
} | {"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}}full{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}} |
| 21 | run_command | {
"command": "grep -rn \"Unable to serialize\" ."
} | {"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}}full{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}} |
| 22 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n encoded = jsonable_encoder(model)\n print(f'Encoded: {encoded}')\nexcept Exception as e:\n import traceback\n traceback.print_exc()\n\""
} | {"status": "ok", "stdout": "", "exit_code": 0}full{"status": "ok", "stdout": "", "exit_code": 0} |
| 23 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\nimport traceback\nimport sys\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n encoded = jsonable_encoder(model)\n print(f'Encoded: {encoded}')\nexcept Exception as e:\n traceback.print_exc()\n\""
} | {"status": "ok", "stdout": "", "exit_code": 0}full{"status": "ok", "stdout": "", "exit_code": 0} |
| 24 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\nimport traceback\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n encoded = jsonable_encoder(model)\n print(f'Encoded: {encoded}')\nexcept Exception:\n traceback.print_exc()\n\""
} | {"status": "ok", "stdout": "", "exit_code": 0}full{"status": "ok", "stdout": "", "exit_code": 0} |
| 25 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\nimport traceback\nimport sys\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n print('Calling jsonable_encoder...')\n encoded = jsonable_encoder(model)\n print(f'Encoded: {encoded}')\nexcept Exception as e:\n print(f'Caught Exception: {type(e).__name__}: {e}')\n traceback.print_exc()\n\""
} | {"status": "ok", "stdout": "Calling jsonable_encoder...\nCaught Exception: PydanticSerializationError: Unable to serialize unknown type: <class '__main__.Customfull{"status": "ok", "stdout": "Calling jsonable_encoder...\nCaught Exception: PydanticSerializationError: Unable to serialize unknown type: <class '__main__.Custom'>\n", "exit_code": 0} |
| 26 | read_file | {
"end_line": 250,
"filepath": "fastapi/encoders.py",
"start_line": 210
} | {"status": "ok", "filepath": "fastapi/encoders.py", "content": " You can also use it yourself, for example to convert objects before saving them\n in a databasefull{"status": "ok", "filepath": "fastapi/encoders.py", "content": " You can also use it yourself, for example to convert objects before saving them\n in a database that supports only JSON.\n\n Read more about it in the\n [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).\n \"\"\"\n custom_encoder = custom_encoder or {}\n if custom_encoder:\n if type(obj) in custom_encoder:\n return custom_encoder[type(obj)](obj)\n else:\n for encoder_type, encoder_instance in custom_encoder.items():\n if isinstance(obj, encoder_type):\n return encoder_instance(obj)\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n if isinstance(obj, (BaseModel, may_v1.BaseModel)):\n # TODO: remove when deprecating Pydantic v1\n encoders: Dict[Any, Any] = {}\n if isinstance(obj, may_v1.BaseModel):\n encoders = getattr(obj.__config__, \"json_encoders\", {}) # type: ignore[attr-defined]\n if custom_encoder:\n encoders = {**encoders, **custom_encoder}\n obj_dict = _model_dump(\n obj,\n mode=\"json\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n", "start_line": 210, "end_line": 250, "total_lines": 356, "is_truncated": false} |
| 27 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n # Test if mode='python' in _model_dump (called by jsonable_encoder)\n # would avoid the serialization error but might return the object itself.\n from fastapi.encoders import _model_dump\n res = _model_dump(model, mode='python')\n print(f'Mode python result: {res}')\n res_json = _model_dump(model, mode='json')\n print(f'Mode json result: {res_json}')\nexcept Exception as e:\n print(f'Error: {e}')\n\""
} | {"status": "ok", "stdout": "Mode python result: {'x': Custom(123)}\nError: Unable to serialize unknown type: <class '__main__.Custom'>\n", "exit_code": 0}full{"status": "ok", "stdout": "Mode python result: {'x': Custom(123)}\nError: Unable to serialize unknown type: <class '__main__.Custom'>\n", "exit_code": 0} |
| 28 | read_file | {
"end_line": 260,
"filepath": "fastapi/encoders.py",
"start_line": 235
} | {"status": "ok", "filepath": "fastapi/encoders.py", "content": " obj_dict = _model_dump(\n obj,\n mode=\"json\",\n include=include,\n exclude=exclude,\n by_aliafull{"status": "ok", "filepath": "fastapi/encoders.py", "content": " obj_dict = _model_dump(\n obj,\n mode=\"json\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n # TODO: remove when deprecating Pydantic v1\n custom_encoder=encoders,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if dataclasses.is_dataclass(obj):\n assert not isinstance(obj, type)\n obj_dict = dataclasses.asdict(obj)\n return jsonable_encoder(\n obj_dict,\n include=include,\n", "start_line": 235, "end_line": 260, "total_lines": 356, "is_truncated": false} |
| 29 | edit_file | {
"filepath": "fastapi/encoders.py",
"new_string": " obj_dict = _model_dump(\\n obj,\\n mode=\\\"python\\\",\\n include=include,\\n exclude=exclude,\\n by_alias=by_alias,\\n exclude_unset=exclude_unset,\\n exclude_none=exclude_none,\\n exclude_defaults=exclude_defaults,\\n )",
"old_string": " obj_dict = _model_dump(\\n obj,\\n mode=\\\"json\\\",\\n include=include,\\n exclude=exclude,\\n by_alias=by_alias,\\n exclude_unset=exclude_unset,\\n exclude_none=exclude_none,\\n exclude_defaults=exclude_defaults,\\n )"
} | {"status": "error", "error_type": "FileEditError", "error_message": "old_string not found in file (tried exact, flexible and regex matching)"}full{"status": "error", "error_type": "FileEditError", "error_message": "old_string not found in file (tried exact, flexible and regex matching)"} |
| 30 | read_file | {
"end_line": 250,
"filepath": "fastapi/encoders.py",
"start_line": 230
} | {"status": "ok", "filepath": "fastapi/encoders.py", "content": " encoders: Dict[Any, Any] = {}\n if isinstance(obj, may_v1.BaseModel):\n encoders = getattr(obj.full{"status": "ok", "filepath": "fastapi/encoders.py", "content": " encoders: Dict[Any, Any] = {}\n if isinstance(obj, may_v1.BaseModel):\n encoders = getattr(obj.__config__, \"json_encoders\", {}) # type: ignore[attr-defined]\n if custom_encoder:\n encoders = {**encoders, **custom_encoder}\n obj_dict = _model_dump(\n obj,\n mode=\"json\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n", "start_line": 230, "end_line": 250, "total_lines": 356, "is_truncated": false} |
| 31 | edit_file | {
"filepath": "fastapi/encoders.py",
"new_string": " obj_dict = _model_dump(\n obj,\n mode=\"python\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )",
"old_string": " obj_dict = _model_dump(\n obj,\n mode=\"json\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )"
} | {"status": "ok", "filepath": "fastapi/encoders.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/fastapi/encoders.py\n+++ b/fastapi/encoders.py\n@@ -23full{"status": "ok", "filepath": "fastapi/encoders.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/fastapi/encoders.py\n+++ b/fastapi/encoders.py\n@@ -234,7 +234,7 @@\n encoders = {**encoders, **custom_encoder}\n obj_dict = _model_dump(\n obj,\n- mode=\"json\",\n+ mode=\"python\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n", "is_truncated": false} |
| 32 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass Custom:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f'Custom({self.val})'\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: Custom\n\ncustom_instance = Custom(123)\nmodel = Model(x=custom_instance)\n\ntry:\n encoded = jsonable_encoder(model)\n print(f'Encoded: {encoded}')\nexcept Exception as e:\n import traceback\n traceback.print_exc()\n\""
} | {"status": "ok", "stdout": "Encoded: {'x': {'val': 123}}\n", "exit_code": 0}full{"status": "ok", "stdout": "Encoded: {'x': {'val': 123}}\n", "exit_code": 0} |
| 33 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass Model(BaseModel):\n x: int\n\nmodel = Model(x=1)\nprint(f'Encoded Model: {jsonable_encoder(model)}')\n\""
} | {"status": "ok", "stdout": "Encoded Model: {'x': 1}\n", "exit_code": 0}full{"status": "ok", "stdout": "Encoded Model: {'x': 1}\n", "exit_code": 0} |
| 34 | run_command | {
"command": "python3 -c \"\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: int\n\nmodel = Model(x=1)\nprint(f'Encoded Model: {jsonable_encoder(model)}')\n\""
} | {"status": "ok", "stdout": "Encoded Model: {'x': 1}\n", "exit_code": 0}full{"status": "ok", "stdout": "Encoded Model: {'x': 1}\n", "exit_code": 0} |
| 35 | submit_patch | [] | {"status": "ok", "patch_size": 437, "files_changed": 1}full{"status": "ok", "patch_size": 437, "files_changed": 1} |
diff --git a/fastapi/encoders.py b/fastapi/encoders.py
index 79395108..ec754986 100644
--- a/fastapi/encoders.py
+++ b/fastapi/encoders.py
@@ -234,7 +234,7 @@ def jsonable_encoder(
encoders = {**encoders, **custom_encoder}
obj_dict = _model_dump(
obj,
- mode="json",
+ mode="python",
include=include,
exclude=exclude,
by_alias=by_alias,
)
<string>:6: in __init__
???
fastapi/_compat/v2.py:97: in __post_init__
self._type_adapter: TypeAdapter[Any] = TypeAdapter(
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/type_adapter.py:244: in __init__
self._init_core_attrs(
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/type_adapter.py:306: in _init_core_attrs
core_schema = schema_generator.generate_schema(self._type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:744: in generate_schema
schema = self._generate_schema_inner(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:1022: in _generate_schema_inner
return self._annotated_schema(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2202: in _annotated_schema
schema = self._apply_annotations(source_type, annotations)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2252: in _apply_annotations
schema = get_inner_schema(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py:83: in __call__
schema = self._handler(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2425: in new_handler
schema = get_inner_schema(source)
^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py:83: in __call__
schema = self._handler(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2423: in new_handler
schema = annotation_get_schema(source, get_inner_schema)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/functional_serializers.py:64: in __get_pydantic_core_schema__
schema = handler(source_type)
^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py:83: in __call__
schema = self._handler(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2425: in new_handler
schema = get_inner_schema(source)
^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py:83: in __call__
schema = self._handler(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2231: in inner_handler
schema = self._generate_schema_inner(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:1043: in _generate_schema_inner
return self.match_type(obj)
^^^^^^^^^^^^^^^^^^^^
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:1165: in match_type
return self._unknown_type_schema(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <pydantic._internal._generate_schema.GenerateSchema object at 0x7f902bc879c0>
obj = <class 'tests.test_arbitrary_types.get_client.<locals>.FakeNumpyArray'>
def _unknown_type_schema(self, obj: Any) -> CoreSchema:
> raise PydanticSchemaGenerationError(
f'Unable to generate pydantic-core schema for {obj!r}. '
'Set `arbitrary_types_allowed=True` in the model_config to ignore this error'
' or implement `__get_pydantic_core_schema__` on your type to fully support it.'
'\n\nIf you got this error by calling handler(<some type>) within'
' `__get_pydantic_core_schema__` then you likely need to call'
' `handler.generate_schema(<some type>)` since we do not call'
' `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.'
)
E pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'tests.test_arbitrary_types.get_client.<locals>.FakeNumpyArray'>. Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.
E
E If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.
E
E For further information visit https://errors.pydantic.dev/2.13/u/schema-for-unknown-type
/kaggle/tmp/envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:674: PydanticSchemaGenerationError
=============================== warnings summary ===============================
../../../../../../kaggle/tmp/envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45
/kaggle/tmp/envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45: DeprecationWarning: The anyio.abc.BlockingPortal alias is deprecated, use anyio.from_thread.BlockingPortal instead.
_PortalFactoryType = Callable[[], AbstractContextManager[anyio.abc.BlockingPortal]]
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
1 failed, 2 passed, 1 warning in 1.12s