Skip to content

Commit 0cc19d7

Browse files
authored
Merge pull request #74 from eadwinCode/linting_with_ruff
Linting with Ruff
2 parents 9e4ba3d + f742009 commit 0cc19d7

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+361
-340
lines changed

.github/workflows/test_full.yml

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,14 @@ jobs:
3434
- name: Set up Python
3535
uses: actions/setup-python@v4
3636
with:
37-
python-version: 3.9
37+
python-version: 3.8
3838
- name: Install Flit
3939
run: pip install flit
4040
- name: Install Dependencies
4141
run: flit install --symlink
4242
- name: Black
4343
run: black --check ninja_extra tests
44-
- name: isort
45-
run: isort --check ninja_extra tests
46-
- name: Flake8
47-
run: flake8 ninja_extra tests
44+
- name: Ruff Linting Check
45+
run: ruff check ninja_extra tests
4846
- name: mypy
4947
run: mypy ninja_extra

Makefile

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,14 @@ install: ## Install dependencies
1818
lint: ## Run code linters
1919
make clean
2020
black --check ninja_extra tests
21-
isort --check ninja_extra tests
22-
flake8 ninja_extra tests
21+
ruff check ninja_extra tests
2322
mypy ninja_extra
2423

2524
fmt format: ## Run code formatters
2625
make clean
2726
black ninja_extra tests
28-
isort ninja_extra tests
27+
ruff check --fix ninja_extra tests
28+
2929

3030
test: ## Run tests
3131
make clean

mypy.ini

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[mypy]
2-
python_version = 3.6
2+
python_version = 3.8
33

44
show_column_numbers = True
55

@@ -19,4 +19,4 @@ check_untyped_defs = True
1919
no_implicit_reexport = True
2020

2121
[mypy-ninja_extra.compatible.*]
22-
ignore_errors = True
22+
ignore_errors = True

ninja_extra/conf/settings.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from typing import Any, Dict, List, Optional
22

33
from django.conf import settings as django_settings
4-
from django.test.signals import setting_changed
4+
from django.core.signals import setting_changed
55
from ninja import Schema
66
from pydantic import Field, root_validator, validator
77

@@ -13,17 +13,17 @@ def __init__(self, data: dict) -> None:
1313
self.__dict__ = data
1414

1515

16-
NinjaExtra_SETTINGS_DEFAULTS = dict(
17-
INJECTOR_MODULES=[],
18-
PAGINATION_CLASS="ninja_extra.pagination.LimitOffsetPagination",
19-
THROTTLE_CLASSES=[
16+
NinjaExtra_SETTINGS_DEFAULTS = {
17+
"INJECTOR_MODULES": [],
18+
"PAGINATION_CLASS": "ninja_extra.pagination.LimitOffsetPagination",
19+
"THROTTLE_CLASSES": [
2020
"ninja_extra.throttling.AnonRateThrottle",
2121
"ninja_extra.throttling.UserRateThrottle",
2222
],
23-
THROTTLE_RATES={"user": None, "anon": None},
24-
ORDERING_CLASS="ninja_extra.ordering.Ordering",
25-
SEARCHING_CLASS="ninja_extra.searching.Searching",
26-
)
23+
"THROTTLE_RATES": {"user": None, "anon": None},
24+
"ORDERING_CLASS": "ninja_extra.ordering.Ordering",
25+
"SEARCHING_CLASS": "ninja_extra.searching.Searching",
26+
}
2727

2828
USER_SETTINGS = UserDefinedSettingsMapper(
2929
getattr(django_settings, "NINJA_EXTRA", NinjaExtra_SETTINGS_DEFAULTS)

ninja_extra/controllers/base.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@
2121

2222
from django.db.models import Model, QuerySet
2323
from django.http import HttpResponse
24-
from django.urls import URLPattern, path as django_path
24+
from django.urls import URLPattern
25+
from django.urls import path as django_path
2526
from injector import inject, is_decorated_with_inject
2627
from ninja import NinjaAPI, Router
2728
from ninja.constants import NOT_SET
@@ -143,7 +144,7 @@ def permission_denied(cls, permission: BasePermission) -> None:
143144
def get_object_or_exception(
144145
self,
145146
klass: Union[Type[Model], QuerySet],
146-
error_message: str = None,
147+
error_message: Optional[str] = None,
147148
exception: Type[APIException] = NotFound,
148149
**kwargs: Any,
149150
) -> Any:
@@ -267,7 +268,6 @@ def __init__(
267268
permissions: Optional["PermissionType"] = None,
268269
auto_import: bool = True,
269270
) -> None:
270-
271271
self.prefix = prefix
272272
# `auth` primarily defines APIController route function global authentication method.
273273
self.auth: Optional[AuthBase] = auth
@@ -278,8 +278,8 @@ def __init__(
278278
# `controller_class` target class that the APIController wraps
279279
self._controller_class: Optional[Type["ControllerBase"]] = None
280280
# `_path_operations` a converted dict of APIController route function used by Django-Ninja library
281-
self._path_operations: Dict[str, ControllerPathView] = dict()
282-
self._controller_class_route_functions: Dict[str, RouteFunction] = dict()
281+
self._path_operations: Dict[str, ControllerPathView] = {}
282+
self._controller_class_route_functions: Dict[str, RouteFunction] = {}
283283
# `permission_classes` a collection of BasePermission Types
284284
# a fallback if route functions has no permissions definition
285285
self.permission_classes: PermissionType = permissions or [AllowAny]

ninja_extra/controllers/registry.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,7 @@
55

66

77
class ControllerBorg:
8-
_shared_state_: Dict[str, Dict[str, Type["ControllerBase"]]] = dict(
9-
controllers=dict()
10-
)
8+
_shared_state_: Dict[str, Dict[str, Type["ControllerBase"]]] = {"controllers": {}}
119

1210
def __init__(self) -> None:
1311
self.__dict__ = self._shared_state_
@@ -27,11 +25,11 @@ def remove_controller(
2725
return None
2826

2927
def clear_controller(self) -> None:
30-
self._shared_state_["controllers"] = dict()
28+
self._shared_state_["controllers"] = {}
3129

3230
@classmethod
3331
def get_controllers(cls) -> Dict[str, Type["ControllerBase"]]:
34-
return cls._shared_state_.get("controllers", dict())
32+
return cls._shared_state_.get("controllers", {})
3533

3634

3735
class ControllerRegistry(ControllerBorg):

ninja_extra/controllers/response.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
SCHEMA_KEY = "_schema"
2121

2222
if sys.version_info < (3, 7): # pragma: no cover
23-
from typing import GenericMeta
23+
from typing import GenericMeta # type: ignore[attr-defined]
2424

2525
class ControllerResponseMeta(GenericMeta):
2626
@no_type_check
@@ -42,7 +42,6 @@ class GenericControllerResponse(metaclass=ControllerResponseMeta):
4242
def __new__(
4343
cls: Type["ControllerResponse[T]"], *args: Any, **kwargs: Any
4444
) -> "ControllerResponse[T]":
45-
4645
if cls._gorg is Generic or "_schema" not in cls.__dict__:
4746
raise TypeError(
4847
"Type Generic cannot be instantiated; "
@@ -62,10 +61,9 @@ class ControllerResponseMeta(type):
6261
pass
6362

6463
class GenericControllerResponse(metaclass=ControllerResponseMeta):
65-
def __new__(
64+
def __new__( # type:ignore[misc]
6665
cls: Type["ControllerResponse[T]"], *args: Any, **kwargs: Any
6766
) -> "ControllerResponse[T]":
68-
6967
if "_schema" not in cls.__dict__:
7068
raise TypeError(
7169
"Type Generic cannot be instantiated; "
@@ -123,7 +121,7 @@ class Id(ControllerResponse[T]):
123121
==> 201, {id: "883a1a3d-7b10-458d-bccc-f9b7219342c9"}
124122
"""
125123

126-
_schema = IdSchema[Any] # type: ignore
124+
_schema = IdSchema[Any]
127125
status_code: int = status.HTTP_201_CREATED
128126

129127
def __init__(self, id: T) -> None:
@@ -156,7 +154,7 @@ class ASchema(BaseModel):
156154
"""
157155

158156
status_code: int = status.HTTP_200_OK
159-
_schema = OkSchema[Any] # type: ignore
157+
_schema = OkSchema[Any]
160158

161159
def __init__(self, message: Optional[Any] = None) -> None:
162160
super(Ok, self).__init__()
@@ -186,7 +184,7 @@ class ErrorSchema(BaseModel):
186184
"""
187185

188186
status_code: int = status.HTTP_200_OK
189-
_schema = DetailSchema[Any] # type: ignore
187+
_schema = DetailSchema[Any]
190188

191189
def __init__(
192190
self, message: Optional[Any] = None, status_code: int = status.HTTP_200_OK

ninja_extra/controllers/route/__init__.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,10 @@ def __init__(
6767
] = None,
6868
openapi_extra: Optional[Dict[str, Any]] = None,
6969
) -> None:
70-
7170
if not isinstance(methods, list):
7271
raise RouteInvalidParameterException("methods must be a list")
7372

74-
methods = list(map(lambda m: m.upper(), methods))
73+
methods = [m.upper() for m in methods]
7574
not_valid_methods = list(set(methods) - set(ROUTE_METHODS))
7675
if not_valid_methods:
7776
raise RouteInvalidParameterException(
@@ -85,7 +84,7 @@ def __init__(
8584
response = cast(ControllerResponse, response)
8685
_response = {response.status_code: response.get_schema()}
8786
elif isinstance(response, list):
88-
_response_computed = dict()
87+
_response_computed = {}
8988
for item in response:
9089
if (
9190
inspect.isclass(item) and type(item) == ControllerResponseMeta

ninja_extra/controllers/route/context.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
from typing import Any, List, Union
1+
from typing import Any, List, Optional, Union
22

33
from django.http import HttpResponse
44
from django.http.request import HttpRequest
55
from ninja.types import DictStrAny
6-
from pydantic import BaseModel as PydanticModel, Field
6+
from pydantic import BaseModel as PydanticModel
7+
from pydantic import Field
78

89
from ninja_extra.types import PermissionType
910

@@ -25,17 +26,19 @@ class Config:
2526

2627
def get_route_execution_context(
2728
request: HttpRequest,
28-
temporal_response: HttpResponse = None,
29-
permission_classes: PermissionType = [],
29+
temporal_response: Optional[HttpResponse] = None,
30+
permission_classes: Optional[PermissionType] = None,
3031
*args: Any,
3132
**kwargs: Any,
3233
) -> RouteContext:
33-
init_kwargs = dict(
34-
permission_classes=permission_classes,
35-
request=request,
36-
kwargs=kwargs,
37-
response=temporal_response,
38-
args=args,
39-
)
40-
context = RouteContext(**init_kwargs)
34+
init_kwargs = {
35+
"permission_classes": permission_classes
36+
if permission_classes is not None
37+
else [],
38+
"request": request,
39+
"kwargs": kwargs,
40+
"response": temporal_response,
41+
"args": args,
42+
}
43+
context = RouteContext(**init_kwargs) # type:ignore[arg-type]
4144
return context

ninja_extra/controllers/route/route_functions.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def __init__(
4040
def __call__(
4141
self,
4242
request: HttpRequest,
43-
temporal_response: HttpResponse = None,
43+
temporal_response: Optional[HttpResponse] = None,
4444
*args: Any,
4545
**kwargs: Any,
4646
) -> Any:
@@ -79,7 +79,7 @@ def _resolve_api_func_signature_(self, context_func: Callable) -> Callable:
7979
def get_view_function(self) -> Callable:
8080
def as_view(
8181
request: HttpRequest,
82-
context: RouteContext = None,
82+
context: Optional[RouteContext] = None,
8383
*args: Any,
8484
**kwargs: Any,
8585
) -> Any:
@@ -124,14 +124,14 @@ def get_route_execution_context(
124124
)
125125
_api_controller = self.get_api_controller()
126126

127-
init_kwargs = dict(
128-
permission_classes=self.route.permissions
127+
init_kwargs = {
128+
"permission_classes": self.route.permissions
129129
or _api_controller.permission_classes,
130-
request=request,
131-
kwargs=kwargs,
132-
args=args,
133-
)
134-
context = RouteContext(**init_kwargs)
130+
"request": request,
131+
"kwargs": kwargs,
132+
"args": args,
133+
}
134+
context = RouteContext(**init_kwargs) # type:ignore[arg-type]
135135
return context
136136

137137
@contextmanager
@@ -166,7 +166,7 @@ class AsyncRouteFunction(RouteFunction):
166166
def get_view_function(self) -> Callable:
167167
async def as_view(
168168
request: HttpRequest,
169-
context: RouteContext = None,
169+
context: Optional[RouteContext] = None,
170170
*args: Any,
171171
**kwargs: Any,
172172
) -> Any:
@@ -191,15 +191,16 @@ def __repr__(self) -> str: # pragma: no cover
191191
async def __call__(
192192
self,
193193
request: HttpRequest,
194-
temporal_response: HttpResponse = None,
194+
temporal_response: Optional[HttpResponse] = None,
195195
*args: Any,
196196
**kwargs: Any,
197197
) -> Any:
198198
_api_controller = self.get_api_controller()
199199
context = get_route_execution_context(
200200
request,
201201
temporal_response,
202-
self.route.permissions or _api_controller.permission_classes, # type: ignore[arg-type]
202+
self.route.permissions
203+
or _api_controller.permission_classes, # type:ignore[arg-type]
203204
*args,
204205
**kwargs,
205206
)

0 commit comments

Comments
 (0)