Skip to content

Commit

Permalink
Common: Extract method DIContainer._resolve_default()
Browse files Browse the repository at this point in the history
  • Loading branch information
mssalvatore committed Mar 7, 2023
1 parent 5d3779d commit 2c75d17
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions monkey/common/di_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def resolve(self, type_: Type[T]) -> T:
:raises UnresolvableDependencyError: If any dependencies could not be successfully resolved
"""
with suppress(UnresolvableDependencyError):
return self._resolve_type(type_, inspect.Parameter.empty)
return self._resolve_type(type_)

args = self.resolve_dependencies(type_)
return type_(*args)
Expand All @@ -148,7 +148,18 @@ def resolve_dependencies(self, type_: Type[T]) -> Sequence[Any]:
args.append(self._resolve_convention(parameter.annotation, parameter.name))
continue

args.append(self._resolve_type(parameter.annotation, parameter.default))
with suppress(UnresolvableDependencyError):
args.append(self._resolve_type(parameter.annotation))
continue

with suppress(UnresolvableDependencyError):
args.append(self._resolve_default(parameter))
continue

raise UnresolvableDependencyError(
f"Failed to resolve dependency {parameter.name} of type "
f"{DIContainer._format_type_name(parameter.annotation)}"
)

return tuple(args)

Expand All @@ -161,16 +172,13 @@ def _resolve_convention(self, type_: Type[T], name: str) -> T:
f"Failed to resolve unregistered convention {convention_identifier}"
)

def _resolve_type(self, type_: Type[T], default: T) -> T:
def _resolve_type(self, type_: Type[T]) -> T:
if type_ in self._type_registry:
return self._construct_new_instance(type_)

if type_ in self._instance_registry:
return self._retrieve_registered_instance(type_)

if default is not inspect.Parameter.empty:
return default

raise UnresolvableDependencyError(
f'Failed to resolve unregistered type "{DIContainer._format_type_name(type)}"'
)
Expand All @@ -186,6 +194,14 @@ def _construct_new_instance(self, arg_type: Type[T]) -> T:
def _retrieve_registered_instance(self, arg_type: Type[T]) -> T:
return self._instance_registry[arg_type]

def _resolve_default(self, parameter: inspect.Parameter) -> Any:
if parameter.default is not inspect.Parameter.empty:
return parameter.default

raise UnresolvableDependencyError(
f'No default found for "{parameter.name}:{DIContainer._format_type_name(type)}"'
)

def release(self, interface: Type[T]):
"""
Deregister an interface
Expand Down

0 comments on commit 2c75d17

Please sign in to comment.