Browse Source

various type fixes and cleanup

pull/15443/head
svlandeg 4 weeks ago
parent
commit
d501f8da96
  1. 4
      fastapi/_compat/shared.py
  2. 12
      fastapi/_compat/v2.py
  3. 10
      fastapi/applications.py
  4. 2
      fastapi/cli.py
  5. 6
      fastapi/dependencies/utils.py
  6. 8
      fastapi/encoders.py
  7. 4
      fastapi/openapi/models.py
  8. 2
      fastapi/openapi/utils.py
  9. 12
      fastapi/params.py
  10. 4
      fastapi/responses.py
  11. 8
      fastapi/routing.py

4
fastapi/_compat/shared.py

@ -23,7 +23,7 @@ _T = TypeVar("_T")
# Copy from Pydantic: pydantic/_internal/_typing_extra.py
WithArgsTypes: tuple[Any, ...] = (
typing._GenericAlias, # type: ignore[attr-defined]
typing._GenericAlias, # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]
types.GenericAlias,
types.UnionType,
) # pyright: ignore[reportAttributeAccessIssue]
@ -48,7 +48,7 @@ def lenient_issubclass(
cls: Any, class_or_tuple: type[_T] | tuple[type[_T], ...] | None
) -> TypeGuard[type[_T]]:
try:
return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type]
return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type] # ty: ignore[invalid-argument-type]
except TypeError: # pragma: no cover
if isinstance(cls, WithArgsTypes):
return False

12
fastapi/_compat/v2.py

@ -23,7 +23,7 @@ from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationEr
from pydantic import PydanticUndefinedAnnotation as PydanticUndefinedAnnotation
from pydantic import ValidationError as ValidationError
from pydantic._internal import _typing_extra as _pydantic_typing_extra
from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined] # ty: ignore[unused-ignore-comment]
from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined]
GetJsonSchemaHandler as GetJsonSchemaHandler,
)
from pydantic.fields import FieldInfo as FieldInfo
@ -372,8 +372,8 @@ def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
continue
origin_type = get_origin(union_arg) or union_arg
break
assert issubclass(origin_type, shared.sequence_types) # type: ignore[arg-type]
return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return,index]
assert issubclass(origin_type, shared.sequence_types) # type: ignore[arg-type] # ty: ignore[invalid-argument-type]
return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return,index] # ty: ignore[invalid-return-type]
def get_missing_field_error(loc: tuple[int | str, ...]) -> dict[str, Any]:
@ -381,14 +381,14 @@ def get_missing_field_error(loc: tuple[int | str, ...]) -> dict[str, Any]:
"Field required", [{"type": "missing", "loc": loc, "input": {}}]
).errors(include_url=False)[0]
error["input"] = None
return error # type: ignore[return-value]
return error # type: ignore[return-value] # ty: ignore[invalid-return-type]
def create_body_model(
*, fields: Sequence[ModelField], model_name: str
) -> type[BaseModel]:
field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields}
BodyModel: type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload]
BodyModel: type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] # ty: ignore[no-matching-overload]
return BodyModel
@ -451,7 +451,7 @@ def get_flat_models_from_annotation(
for arg in get_args(annotation):
if lenient_issubclass(arg, (BaseModel, Enum)):
if arg not in known_models:
known_models.add(arg) # type: ignore[arg-type] # ty: ignore[unused-ignore-comment]
known_models.add(arg) # type: ignore[arg-type]
if lenient_issubclass(arg, BaseModel):
get_flat_models_from_model(arg, known_models=known_models)
else:

10
fastapi/applications.py

@ -1006,7 +1006,7 @@ class FastAPI(Starlette):
# Starlette still has incorrect type specification for the handlers
self.exception_handlers.setdefault(
WebSocketRequestValidationError,
websocket_request_validation_exception_handler, # type: ignore[arg-type] # ty: ignore[unused-ignore-comment]
websocket_request_validation_exception_handler, # type: ignore[arg-type]
) # ty: ignore[no-matching-overload]
self.user_middleware: list[Middleware] = (
@ -1029,11 +1029,11 @@ class FastAPI(Starlette):
exception_handlers[key] = value
middleware = (
[Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] # ty: ignore[invalid-argument-type]
[Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
+ self.user_middleware
+ [
Middleware(
ExceptionMiddleware, # ty: ignore[invalid-argument-type]
ExceptionMiddleware,
handlers=exception_handlers,
debug=debug,
),
@ -1056,7 +1056,7 @@ class FastAPI(Starlette):
# user middlewares, the same context is used.
# This is currently not needed, only for closing files, but used to be
# important when dependencies with yield were closed here.
Middleware(AsyncExitStackMiddleware), # ty: ignore[invalid-argument-type]
Middleware(AsyncExitStackMiddleware),
]
)
@ -4638,7 +4638,7 @@ class FastAPI(Starlette):
"""
def decorator(func: DecoratedCallable) -> DecoratedCallable:
self.add_middleware(BaseHTTPMiddleware, dispatch=func) # ty: ignore[invalid-argument-type]
self.add_middleware(BaseHTTPMiddleware, dispatch=func)
return func
return decorator

2
fastapi/cli.py

@ -6,7 +6,7 @@ except ImportError: # pragma: no cover
def main() -> None:
if not cli_main: # type: ignore[truthy-function] # ty: ignore[unused-ignore-comment]
if not cli_main: # type: ignore[truthy-function]
message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n'
print(message)
raise RuntimeError(message) # noqa: B904

6
fastapi/dependencies/utils.py

@ -100,14 +100,14 @@ def ensure_multipart_is_installed() -> None:
except (ImportError, AssertionError):
try:
# __version__ is available in both multiparts, and can be mocked
from multipart import ( # type: ignore[no-redef,import-untyped] # ty: ignore[unused-ignore-comment]
from multipart import ( # type: ignore[no-redef,import-untyped]
__version__,
)
assert __version__
try:
# parse_options_header is only available in the right multipart
from multipart.multipart import ( # type: ignore[import-untyped] # ty: ignore[unused-ignore-comment]
from multipart.multipart import ( # type: ignore[import-untyped]
parse_options_header,
)
@ -622,7 +622,7 @@ async def solve_dependencies(
if response is None:
response = Response()
del response.headers["content-length"]
response.status_code = None # type: ignore # ty: ignore[unused-ignore-comment]
response.status_code = None # type: ignore
if dependency_cache is None:
dependency_cache = {}
for sub_dependant in dependant.dependencies:

8
fastapi/encoders.py

@ -36,7 +36,7 @@ try:
from pydantic.color import Color # ty: ignore[deprecated]
except ImportError: # pragma: no cover
class Color: # type: ignore[no-redef] # ty: ignore[unused-ignore-comment]
class Color: # type: ignore[no-redef]
pass
@ -45,7 +45,7 @@ try:
from pydantic_extra_types.color import Color as PyExtraColor
except ImportError: # pragma: no cover
class PyExtraColor: # type: ignore[no-redef] # ty: ignore[unused-ignore-comment]
class PyExtraColor: # type: ignore[no-redef]
pass
@ -237,9 +237,9 @@ def jsonable_encoder(
if isinstance(obj, encoder_type):
return encoder_instance(obj)
if include is not None and not isinstance(include, (set, dict)):
include = set(include) # type: ignore[assignment] # ty: ignore[unused-ignore-comment]
include = set(include) # type: ignore[assignment]
if exclude is not None and not isinstance(exclude, (set, dict)):
exclude = set(exclude) # type: ignore[assignment] # ty: ignore[unused-ignore-comment]
exclude = set(exclude) # type: ignore[assignment]
if isinstance(obj, BaseModel):
obj_dict = obj.model_dump(
mode="json",

4
fastapi/openapi/models.py

@ -20,7 +20,7 @@ try:
from pydantic import EmailStr
except ImportError: # pragma: no cover
class EmailStr(str): # type: ignore # ty: ignore[unused-ignore-comment]
class EmailStr(str): # type: ignore[no-redef]
@classmethod
def __get_validators__(cls) -> Iterable[Callable[..., Any]]:
yield cls.validate
@ -215,7 +215,7 @@ class Example(TypedDict, total=False):
value: Any | None
externalValue: AnyUrl | None
__pydantic_config__ = {"extra": "allow"} # type: ignore[misc]
__pydantic_config__ = {"extra": "allow"} # type: ignore[misc] # ty: ignore[invalid-typed-dict-statement]
class ParameterInType(Enum):

2
fastapi/openapi/utils.py

@ -603,4 +603,4 @@ def get_openapi(
output["tags"] = tags
if external_docs:
output["externalDocs"] = external_docs
return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore # ty: ignore[unused-ignore-comment]
return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore

12
fastapi/params.py

@ -134,7 +134,7 @@ class Param(FieldInfo): # type: ignore[misc]
return f"{self.__class__.__name__}({self.default})"
class Path(Param): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
class Path(Param): # type: ignore[misc]
in_ = ParamTypes.path
def __init__(
@ -218,7 +218,7 @@ class Path(Param): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
)
class Query(Param): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
class Query(Param): # type: ignore[misc]
in_ = ParamTypes.query
def __init__(
@ -300,7 +300,7 @@ class Query(Param): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
)
class Header(Param): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
class Header(Param): # type: ignore[misc]
in_ = ParamTypes.header
def __init__(
@ -384,7 +384,7 @@ class Header(Param): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
)
class Cookie(Param): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
class Cookie(Param): # type: ignore[misc]
in_ = ParamTypes.cookie
def __init__(
@ -578,7 +578,7 @@ class Body(FieldInfo): # type: ignore[misc]
return f"{self.__class__.__name__}({self.default})"
class Form(Body): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
class Form(Body): # type: ignore[misc]
def __init__(
self,
default: Any = Undefined,
@ -660,7 +660,7 @@ class Form(Body): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
)
class File(Form): # type: ignore[misc] # ty: ignore[unused-ignore-comment]
class File(Form): # type: ignore[misc]
def __init__(
self,
default: Any = Undefined,

4
fastapi/responses.py

@ -27,13 +27,13 @@ class _OrjsonModule(Protocol):
try:
ujson = cast(_UjsonModule, importlib.import_module("ujson"))
except ModuleNotFoundError: # pragma: nocover
ujson = None # type: ignore # ty: ignore[unused-ignore-comment]
ujson = None # type: ignore
try:
orjson = cast(_OrjsonModule, importlib.import_module("orjson"))
except ModuleNotFoundError: # pragma: nocover
orjson = None # type: ignore # ty: ignore[unused-ignore-comment]
orjson = None # type: ignore
@deprecated(

8
fastapi/routing.py

@ -102,9 +102,9 @@ def request_response(
and returns an ASGI application.
"""
f: Callable[[Request], Awaitable[Response]] = (
func # type: ignore[assignment] # ty: ignore[unused-ignore-comment]
func # type: ignore[assignment]
if is_async_callable(func)
else functools.partial(run_in_threadpool, func) # type: ignore[call-arg] # ty: ignore[unused-ignore-comment]
else functools.partial(run_in_threadpool, func) # type: ignore[call-arg]
) # ty: ignore[invalid-assignment]
async def app(scope: Scope, receive: Receive, send: Send) -> None:
@ -220,7 +220,7 @@ def _merge_lifespan_context(
else:
yield {**(maybe_nested_state or {}), **(maybe_original_state or {})}
return merged_lifespan # type: ignore[return-value]
return merged_lifespan # type: ignore[return-value] # ty: ignore[invalid-return-type]
class _DefaultLifespan:
@ -912,7 +912,7 @@ class APIRoute(routing.Route):
mode="serialization",
)
else:
self.response_field = None # type: ignore # ty: ignore[unused-ignore-comment]
self.response_field = None # type: ignore[assignment]
if self.stream_item_type:
stream_item_name = "StreamItem_" + self.unique_id
self.stream_item_field: ModelField | None = create_model_field(

Loading…
Cancel
Save