Skip to content

Commit eb6ac81

Browse files
committed
Fix Pylance type warnings across codebase
1 parent b483536 commit eb6ac81

6 files changed

Lines changed: 34 additions & 33 deletions

File tree

ml_rest_api/api/model/predict.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
"""This module implements the ModelPredict class."""
22

33
import json
4-
from typing import Type, Dict
5-
from aniso8601 import parse_date, parse_datetime
4+
from typing import Any
5+
from aniso8601 import parse_date, parse_datetime # type: ignore
66
from flask import request
7-
from flask_restx import Resource, Model, fields
7+
from flask_restx import Resource, Model, fields # type: ignore
88
from ml_rest_api.api.restx import api, FlaskApiReturnType, MLRestAPINotReadyException
99
from ml_rest_api.ml_trained_model.wrapper import trained_model_wrapper
1010

@@ -14,19 +14,19 @@ def build_api_model() -> Model:
1414
Returns a Flask-RESTX Api Model based on the sample dict returned by the trained model wrapper.
1515
This will be used to validate input and automatically generate the Swagger prototype.
1616
"""
17-
fields_classes_map: Dict = {
17+
fields_classes_map: dict[str, Any] = {
1818
"str": fields.String,
1919
"int": fields.Integer,
2020
"float": fields.Float,
2121
"bool": fields.Boolean,
2222
"datetime": fields.DateTime,
2323
"date": fields.Date,
2424
}
25-
model_dict: Dict = {}
26-
model_sample: Dict = trained_model_wrapper.sample()
25+
model_dict: dict[str, Any] = {}
26+
model_sample: dict[str, Any] = trained_model_wrapper.sample()
2727
if model_sample:
2828
for key, value in model_sample.items():
29-
fields_class: Type[fields.Raw] = fields_classes_map.get(
29+
fields_class: Any = fields_classes_map.get(
3030
type(value).__name__, fields.String
3131
)
3232
if type(value).__name__ == "str":
@@ -44,14 +44,14 @@ def build_api_model() -> Model:
4444
return api.model("input_vector", model_dict)
4545

4646

47-
ns = api.namespace( # pylint: disable=invalid-name
47+
ns = api.namespace( # pylint: disable=invalid-name # type: ignore[misc]
4848
"model",
4949
description="Methods supported by our ML model",
5050
validate=bool(trained_model_wrapper.sample()),
5151
)
5252

5353

54-
@ns.route("/predict")
54+
@ns.route("/predict") # type: ignore[misc]
5555
class ModelPredict(Resource):
5656
"""Implements the /model/predict POST method."""
5757

ml_rest_api/api/restx.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
"""Module that creates the Api object and declares default error handler."""
22

33
from logging import Logger, getLogger
4-
from typing import Tuple, Dict
4+
from typing import Any
55
from jsonschema import FormatChecker
66
from flask import Blueprint
7-
from flask_restx import Api
7+
from flask_restx import Api # type: ignore
88
from ml_rest_api.settings import get_value
99

1010

@@ -16,7 +16,7 @@ class MLRestAPINotReadyException(MLRestAPIException):
1616
"""Base ML Rest API NOT READY Exception"""
1717

1818

19-
FlaskApiReturnType = Tuple[Dict, int]
19+
FlaskApiReturnType = tuple[dict[str, Any], int]
2020

2121
log: Logger = getLogger(__name__)
2222

@@ -39,15 +39,15 @@ class MLRestAPINotReadyException(MLRestAPIException):
3939
)
4040

4141

42-
@api.errorhandler(MLRestAPINotReadyException)
42+
@api.errorhandler(MLRestAPINotReadyException) # type: ignore[misc]
4343
def not_ready_error_handler() -> FlaskApiReturnType:
4444
"""NOT READY error handler that returns HTTP 503 error."""
4545
log.exception("Server Not Ready")
4646
return {"message": "Server Not Ready"}, 503
4747

4848

49-
@api.errorhandler
50-
def default_error_handler(exception) -> FlaskApiReturnType:
49+
@api.errorhandler # type: ignore[misc]
50+
def default_error_handler(exception: Any) -> FlaskApiReturnType:
5151
"""Default error handler that returns HTTP 500 error."""
5252
log.exception(exception.message)
5353
if get_value("FLASK_DEBUG"):

ml_rest_api/app.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,25 @@
44
import warnings
55
from logging import Logger, getLogger
66
import logging.config
7-
from typing import List
87
from flask import Flask
9-
from flask_wtf import CSRFProtect # pylint: disable=unused-import
8+
from flask_wtf import CSRFProtect # pylint: disable=unused-import # type: ignore
109
from ml_rest_api.settings import get_value
1110
from ml_rest_api.ml_trained_model.wrapper import trained_model_wrapper
1211
from ml_rest_api.api.restx import blueprint
13-
import ml_rest_api.api.health.liveness # pylint: disable=unused-import
14-
import ml_rest_api.api.health.readiness # pylint: disable=unused-import
15-
import ml_rest_api.api.model.predict # pylint: disable=unused-import
12+
import ml_rest_api.api.health.liveness # pylint: disable=unused-import # pyright: ignore[reportUnusedImport]
13+
import ml_rest_api.api.health.readiness # pylint: disable=unused-import # pyright: ignore[reportUnusedImport]
14+
import ml_rest_api.api.model.predict # pylint: disable=unused-import # pyright: ignore[reportUnusedImport]
1615

1716
IN_UWSGI: bool = True # pylint: disable=invalid-name
1817
try:
19-
# pyright: reportMissingImports=false
20-
import uwsgi # pylint: disable=unused-import
18+
import uwsgi # pylint: disable=unused-import # type: ignore
2119
except ImportError:
2220
IN_UWSGI = False # pylint: disable=invalid-name
2321

2422

2523
def configure_app(flask_app: Flask) -> None:
2624
"""Configures the app."""
27-
flask_settings_to_apply: List = [
25+
flask_settings_to_apply: list[str] = [
2826
#'FLASK_SERVER_NAME',
2927
"SWAGGER_UI_DOC_EXPANSION",
3028
"RESTX_VALIDATE",

ml_rest_api/ml_trained_model/wrapper.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
import importlib
66
from threading import Thread
77
from types import ModuleType
8-
from typing import Optional, Iterable, Callable, Dict
8+
from typing import Any, Optional, Iterable, Callable
99
from ml_rest_api.settings import get_value
1010

11-
WrapperCallableType = Optional[Callable]
11+
WrapperCallableType = Optional[Callable[..., Any]]
1212

1313

1414
class TrainedModelWrapper:
@@ -85,13 +85,13 @@ def init(self) -> None:
8585
self._init()
8686
self.initialised = True
8787

88-
def run(self, data: Iterable) -> Dict:
88+
def run(self, data: Iterable[Any]) -> dict[str, Any]:
8989
"""Calls the wrapped run() method if it's assigned."""
9090
if self._run:
9191
return self._run(data)
9292
return {}
9393

94-
def sample(self) -> Dict:
94+
def sample(self) -> dict[str, Any]:
9595
"""Calls the wrapped sample() method if it's assigned."""
9696
if self._sample:
9797
return self._sample()

ml_rest_api/settings.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
"""Settings file."""
22

33
import os
4-
from typing import Any, Dict
4+
from typing import Any
55

66

77
def get_value(key: str) -> Any:
88
"""Returns a value from the corresponding env var or from settings if env var doesn't exist."""
9-
settings: Dict = {
9+
settings: dict[str, Any] = {
1010
# Flask settings
1111
"FLASK_SERVER_NAME": "localhost:8888",
1212
"FLASK_HOST": "0.0.0.0",

tests/basic_test.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from http import HTTPStatus
44
from json import loads
5+
from typing import Any
56
import requests
67
import pytest
78
from openapi_spec_validator import (
@@ -20,7 +21,7 @@
2021
"Content-Type": "application/json",
2122
"Accept": "application/json",
2223
}
23-
GOOD_JSON_DICT = {
24+
GOOD_JSON_DICT: dict[str, Any] = {
2425
"int_param": 12345,
2526
"string_param": "foobar",
2627
"float_param": 123.45,
@@ -34,7 +35,7 @@
3435
NOT_A_DATE_MSG = "is not a 'date'"
3536

3637

37-
def _get_request(url):
38+
def _get_request(url: str):
3839
response = requests.get(
3940
url,
4041
allow_redirects=True,
@@ -43,7 +44,7 @@ def _get_request(url):
4344
return response
4445

4546

46-
def _post_request(url, headers=None, json=None):
47+
def _post_request(url: str, headers: dict[str, str] | None = None, json: Any = None):
4748
response = requests.post(
4849
url,
4950
headers=headers,
@@ -54,7 +55,9 @@ def _post_request(url, headers=None, json=None):
5455
return response
5556

5657

57-
def _post_request_good_json_with_overrides(override_key=None, override_value=None):
58+
def _post_request_good_json_with_overrides(
59+
override_key: str | None = None, override_value: Any = None
60+
):
5861
json_dict = GOOD_JSON_DICT
5962
if override_key is not None:
6063
if override_value is None:

0 commit comments

Comments
 (0)