python
type_error
ai_generated
true
RuntimeError: Dependency cache key must be hashable
ID: python/fastapi-runtimeerror-dependency-cache-key-must-be-hashable
80%Fix Rate
84%Confidence
0Evidence
2024-08-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Using a mutable object (like a list or dict) as a dependency parameter that FastAPI tries to cache.
generic中文
使用可变对象(如列表或字典)作为 FastAPI 尝试缓存的依赖参数。
Workarounds
-
90% success Use immutable types like tuple instead of list.
from typing import Tuple async def dependency(items: Tuple[int, ...] = (1, 2, 3)): return items -
95% success Use Pydantic models for complex parameters.
from pydantic import BaseModel class FilterParams(BaseModel): tags: list[str] = [] async def dependency(params: FilterParams): return params
Dead Ends
Common approaches that don't work:
-
Using a list as a default value for a dependency.
80% fail
Lists are mutable and unhashable, causing caching issues.
-
Using a dict as a query parameter.
70% fail
Query parameters must be hashable; dicts are not.