Skip to content

Commit

Permalink
Fix type hinting in PyCharm (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
RB387 authored Nov 12, 2024
1 parent 4355b16 commit 756d4a0
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 21 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Fixed
- Compatibility with PyCharm for FastAPI `Provide` type hints

### Removed
- Removed `Provider` class

## [0.2.1] - 2024-10-01
### Fixed
Expand Down
4 changes: 2 additions & 2 deletions src/magic_di/fastapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
"""

from ._app import inject_app
from ._provide import Provide, Provider # type: ignore[attr-defined]
from ._provide import Provide # type: ignore[attr-defined]

__all__ = ("inject_app", "Provide", "Provider")
__all__ = ("inject_app", "Provide")
37 changes: 18 additions & 19 deletions src/magic_di/fastapi/_provide.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,25 @@
class FastAPIInjectionError(Exception): ...


class Provider:
def __getitem__(self, obj: type[T]) -> type[T]:
@lru_cache(maxsize=1)
def get_dependency(injector: DependencyInjector) -> T:
return injector.inject(obj)()

def inject(request: Request) -> T:
if not hasattr(request.app.state, "dependency_injector"):
error_msg = (
"FastAPI application is not injected. Did you forget to add `inject_app(app)`?"
)
raise FastAPIInjectionError(error_msg)
if TYPE_CHECKING:
from typing import Union as Provide # hack for mypy # noqa: FIX004
else:

injector = request.app.state.dependency_injector
return get_dependency(injector)
class Provide:
def __class_getitem__(cls, obj: T) -> T:
@lru_cache(maxsize=1)
def get_dependency(injector: DependencyInjector) -> T:
return injector.inject(obj)()

return Annotated[obj, Depends(inject), Injectable] # type: ignore[return-value]
def inject(request: Request) -> T:
if not hasattr(request.app.state, "dependency_injector"):
error_msg = (
"FastAPI application is not injected. "
"Did you forget to add `inject_app(app)`?"
)
raise FastAPIInjectionError(error_msg)

injector = request.app.state.dependency_injector
return get_dependency(injector)

if TYPE_CHECKING:
from typing import Union as Provide # hack for mypy # noqa: FIX004
else:
Provide = Provider()
return Annotated[obj, Depends(inject), Injectable] # type: ignore[return-value]

0 comments on commit 756d4a0

Please sign in to comment.