Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 73 additions & 11 deletions .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,90 @@ include = [
"examples/**.py",
]
exclude = [
"src/dishka/_adaptix/**",
"src/dishka/_adaptix/",
]
lint.typing-extensions = false
lint.select = [
"ALL"

[lint]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[tool.ruff.format]
preview = true

Не хочешь сразу добавить?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тишка не хочет форматтер

# Disable `typing_extensions` imports
typing-extensions = false

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это уже было


preview = true
explicit-preview-rules = true

select = ["ALL"]
extend-select = [
# PEP8
# https://peps.python.org/pep-0008
# https://docs.astral.sh/ruff/rules/#pycodestyle-e-w
"E112",
"E113",
"E114",
"E115",
"E116",
"E117",
"E201",
"E202",
"E203",
"E204",
"E211",
"E221",
"E223",
"E224",
"E225",
"E227",
"E228",
"E231",
"E241",
"E242",
"E251",
"E252",
"E261",
"E262",
"E265",
"E271",
"E272",
"E273",
"E274",
"E301",
"E302",
"E303",
"E304",
"E305",
"E306",
"E502",
# https://docs.astral.sh/ruff/rules/#ruff-specific-rules-ruf
"RUF047",
"RUF052",
"RUF055",
"RUF056",
"RUF063",
"RUF065",
"RUF066",
"RUF068",
"RUF069",
"RUF070",
# https://docs.astral.sh/ruff/rules/#refurb-furb
"FURB118",
"FURB148",
"FURB152",
"FURB156",
]
lint.ignore = [
ignore = [
"ARG",
"ANN",
"ANN401",
"D",
"EM101",
"EM102",
"PT001",
"PT023",
"SIM103",
"SIM108",
"RET505",
"PLR0913",
"SIM103",
"ISC003",
"PERF401",
"FBT003",
"PLW0108",

# identical by code != identical by meaning
"SIM114",

# awful things, never use.
# It makes runtime work differently from typechecker
"TC001",
Expand All @@ -43,9 +101,13 @@ lint.ignore = [

[lint.per-file-ignores]
"tests/**" = [
"ANN",
"PT001",
"PT023",
"TID252",
"PLR2004",
"S101",
"S311",
"TRY003",
"PLW1641",
"PYI059"
Expand Down
10 changes: 5 additions & 5 deletions examples/async_simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,23 @@ class Gateway(Protocol):


class Connection:
async def close(self):
async def close(self) -> None:
print("Connection closed")


class GatewayImplementation(Gateway):
def __init__(self, config: Config, connection: Connection):
def __init__(self, config: Config, connection: Connection) -> None:
self.value = config.value
self.connection = connection

def __repr__(self):
def __repr__(self) -> str:
return f"A(value={self.value}, connection={self.connection})"


class MyProvider(Provider):
scope = Scope.REQUEST

def __init__(self, config: Config):
def __init__(self, config: Config) -> None:
super().__init__()
self.config = config

Expand All @@ -54,7 +54,7 @@ async def get_conn(self) -> AsyncIterable[Connection]:
base_gw = alias(source=GatewayImplementation, provides=Gateway)


async def main():
async def main() -> None:
config = Config(1)
provider = MyProvider(config)
container = make_async_container(provider)
Expand Down
4 changes: 2 additions & 2 deletions examples/integrations/aiogram_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ async def start(
user: FromDishka[User],
value: FromDishka[int],
chat: FromDishka[Chat | None],
):
) -> None:
chat_name = chat.username if chat else None
await message.answer(f"Hello, {value}, {chat_name}, {user.full_name}!")


async def main():
async def main() -> None:
# real main
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
Expand Down
2 changes: 1 addition & 1 deletion examples/integrations/aiohttp_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async def endpoint(
return Response(text=f"gateway data: {data}")


async def on_shutdown(app: Application):
async def on_shutdown(app: Application) -> None:
await app[DISHKA_CONTAINER_KEY].close()


Expand Down
2 changes: 1 addition & 1 deletion examples/integrations/arq/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from arq.connections import RedisSettings


async def main():
async def main() -> None:
pool = await create_pool(RedisSettings())
await pool.enqueue_job("get_content")

Expand Down
2 changes: 1 addition & 1 deletion examples/integrations/arq/run_with_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class GatewayProvider(Provider):
async def get_content(
context: dict[Any, Any],
gateway: FromDishka[Gateway],
):
) -> None:
result = await gateway.get()
logger.info(result)

Expand Down
4 changes: 2 additions & 2 deletions examples/integrations/arq/run_with_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class GatewayProvider(Provider):
async def get_content(
context: dict[Any, Any],
gateway: FromDishka[Gateway],
):
) -> None:
result = await gateway.get()
logger.info(result)

Expand All @@ -35,7 +35,7 @@ class WorkerSettings:
functions = [get_content] # noqa: RUF012


async def main():
async def main() -> None:
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(process)-7s %(module)-20s %(message)s",
Expand Down
21 changes: 15 additions & 6 deletions examples/integrations/click_app/async_command.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import asyncio
from abc import abstractmethod
from collections.abc import Callable, Coroutine
from functools import wraps
from typing import Protocol
from typing import Any, ParamSpec, Protocol, TypeVar

import click
from dishka import (
Expand All @@ -27,7 +28,7 @@ async def get(self) -> str:


class Interactor:
def __init__(self, db: DbGateway):
def __init__(self, db: DbGateway) -> None:
self.db = db

async def __call__(self) -> str:
Expand All @@ -44,17 +45,21 @@ class InteractorProvider(Provider):
i1 = provide(Interactor, scope=Scope.APP)


def async_command(f):
P = ParamSpec("P")
T = TypeVar("T")


def async_command(f: Callable[P, Coroutine[Any, Any, T]]) -> Callable[P, T]:
@wraps(f)
def wrapper(*args, **kwargs):
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
return asyncio.run(f(*args, **kwargs))

return wrapper


@click.group()
@click.pass_context
def main(context: click.Context):
def main(context: click.Context) -> None:
container = make_container(AdaptersProvider(), InteractorProvider())
setup_dishka(container=container, context=context, auto_inject=True)

Expand All @@ -63,7 +68,11 @@ def main(context: click.Context):
@click.option("--count", default=1, help="Number of greetings.")
@click.option("--name", prompt="Your name", help="The person to greet.")
@async_command
async def hello(count: int, name: str, interactor: FromDishka[Interactor]):
async def hello(
count: int,
name: str,
interactor: FromDishka[Interactor],
) -> None:
"""Simple program that greets NAME for a total of COUNT times."""
for _ in range(count):
click.echo(f"Hello {name}!")
Expand Down
6 changes: 3 additions & 3 deletions examples/integrations/click_app/sync_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def get(self) -> str:


class Interactor:
def __init__(self, db: DbGateway):
def __init__(self, db: DbGateway) -> None:
self.db = db

def __call__(self) -> str:
Expand All @@ -37,15 +37,15 @@ class InteractorProvider(Provider):

@click.group()
@click.pass_context
def main(context: click.Context):
def main(context: click.Context) -> None:
container = make_container(AdaptersProvider(), InteractorProvider())
setup_dishka(container=container, context=context, auto_inject=True)


@click.command()
@click.option("--count", default=1, help="Number of greetings.")
@click.option("--name", prompt="Your name", help="The person to greet.")
def hello(count: int, name: str, interactor: FromDishka[Interactor]):
def hello(count: int, name: str, interactor: FromDishka[Interactor]) -> None:
"""Simple program that greets NAME for a total of COUNT times."""
for _ in range(count):
click.echo(f"Hello {name}!")
Expand Down
7 changes: 4 additions & 3 deletions examples/integrations/fastapi_app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
from abc import abstractmethod
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Protocol

Expand Down Expand Up @@ -33,7 +34,7 @@ def get(self) -> str:


class Interactor:
def __init__(self, db: DbGateway):
def __init__(self, db: DbGateway) -> None:
self.db = db

def __call__(self) -> str:
Expand Down Expand Up @@ -77,12 +78,12 @@ async def auto(


@asynccontextmanager
async def lifespan(app: FastAPI):
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
yield
await app.state.dishka_container.close()


def create_app():
def create_app() -> FastAPI:
logging.basicConfig(
level=logging.WARNING,
format="%(asctime)s %(process)-7s %(module)-20s %(message)s",
Expand Down
4 changes: 2 additions & 2 deletions examples/integrations/faststream_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ async def handler(
b: FromDishka[B],
raw_message: FromDishka[NatsMessage],
faststream_context: FromDishka[ContextRepo],
):
) -> None:
print(msg, a, b)


@app.after_startup
async def t():
async def t() -> None:
await broker.publish("test", "test")
2 changes: 1 addition & 1 deletion examples/integrations/flask_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def get(self) -> str:


class Interactor:
def __init__(self, db: DbGateway):
def __init__(self, db: DbGateway) -> None:
self.db = db

def __call__(self) -> str:
Expand Down
2 changes: 1 addition & 1 deletion examples/integrations/grpcio/grpc_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from grpcio.pb2.service_pb2_grpc import ExampleServiceStub


def run():
def run() -> None:
with grpc.insecure_channel("localhost:50051") as channel:
stub = ExampleServiceStub(channel)

Expand Down
4 changes: 2 additions & 2 deletions examples/integrations/litestar_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def get(self) -> str:


class Interactor:
def __init__(self, db: DbGateway):
def __init__(self, db: DbGateway) -> None:
self.db = db

def __call__(self) -> str:
Expand Down Expand Up @@ -51,7 +51,7 @@ async def index(
return interactor()


def create_app():
def create_app() -> Litestar:
logging.basicConfig(
level=logging.WARNING,
format="%(asctime)s %(process)-7s %(module)-20s %(message)s",
Expand Down
4 changes: 2 additions & 2 deletions examples/integrations/starlette_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def get(self) -> str:


class Interactor:
def __init__(self, db: DbGateway):
def __init__(self, db: DbGateway) -> None:
self.db = db

def __call__(self) -> str:
Expand All @@ -51,7 +51,7 @@ async def index(
return PlainTextResponse(result)


def create_app():
def create_app() -> Starlette:
logging.basicConfig(
level=logging.WARNING,
format="%(asctime)s %(process)-7s %(module)-20s %(message)s",
Expand Down
Loading
Loading