Skip to content

Signature cache optimization #880

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
23 changes: 20 additions & 3 deletions src/dependency_injector/wiring.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,9 +591,18 @@ def _extract_marker(parameter: inspect.Parameter) -> Optional["_Marker"]:
return marker


_signature_cache: Dict[int, Tuple[Dict[str, Any], Dict[str, Any]]] = {}


def _fetch_reference_injections( # noqa: C901
fn: Callable[..., Any],
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""Get reference injections with caching."""
# Use the function's id as cache key
fn_id = id(fn)
if fn_id in _signature_cache:
return _signature_cache[fn_id]

# Hotfix, see:
# - https://github.com/ets-labs/python-dependency-injector/issues/362
# - https://github.com/ets-labs/python-dependency-injector/issues/398
Expand All @@ -606,9 +615,13 @@ def _fetch_reference_injections( # noqa: C901
signature = inspect.signature(fn)
except ValueError as exception:
if "no signature found" in str(exception):
return {}, {}
result = {}, {}
_signature_cache[fn_id] = result
return result
elif "not supported by signature" in str(exception):
return {}, {}
result = {}, {}
_signature_cache[fn_id] = result
return result
else:
raise exception

Expand All @@ -625,7 +638,10 @@ def _fetch_reference_injections( # noqa: C901
closing[parameter_name] = marker

injections[parameter_name] = marker
return injections, closing

result = (injections, closing)
_signature_cache[fn_id] = result
return result


def _locate_dependent_closing_args(
Expand Down Expand Up @@ -1036,4 +1052,5 @@ def _patched(*args, **kwargs):
patched.injections,
patched.closing,
)

return cast(F, _patched)