Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use globals of original(wrapped) function #97

Merged
merged 5 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
13 changes: 8 additions & 5 deletions fast_depends/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ def get_typed_signature(call: Callable[..., Any]) -> Tuple[inspect.Signature, An

locals = collect_outer_stack_locals()

# We unwrap call to get the original unwrapped function
while hasattr(call, "__wrapped__"):
call = call.__wrapped__

globalns = getattr(call, "__globals__", {})
typed_params = [
inspect.Parameter(
Expand Down Expand Up @@ -129,12 +133,11 @@ def get_typed_annotation(
if isinstance(annotation, ForwardRef):
annotation = evaluate_forwardref(annotation, globalns, locals)

if (
get_origin(annotation) is Annotated
and (args := get_args(annotation))
):
if get_origin(annotation) is Annotated and (args := get_args(annotation)):
solved_args = [get_typed_annotation(x, globalns, locals) for x in args]
annotation.__origin__, annotation.__metadata__ = solved_args[0], tuple(solved_args[1:])
annotation.__origin__, annotation.__metadata__ = solved_args[0], tuple(
solved_args[1:]
)

return annotation

Expand Down
Empty file added tests/__init__.py
Empty file.
25 changes: 25 additions & 0 deletions tests/test_prebuild.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,36 @@
from __future__ import annotations

from fast_depends.core import build_call_model
from fast_depends.use import inject

from .wrapper import noop_wrap

from pydantic import BaseModel


class Model(BaseModel):
a: str


def base_func(a: int) -> str:
return "success"


def model_func(m: Model) -> str:
return m.a


def test_prebuild():
model = build_call_model(base_func)
inject()(None, model)(1)


def test_prebuild_with_wrapper():
# build_call_model should work even if function is wrapped with a
# wrapper that is imported from different module
func = noop_wrap(model_func)
call_model = build_call_model(func)

assert call_model.model
# Fails if function unwrapping is not done at type introspection
call_model.model.model_rebuild()
11 changes: 11 additions & 0 deletions tests/wrapper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from __future__ import annotations

from functools import wraps


def noop_wrap(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)

return wrapper