Skip to content

Commit 2ab78f3

Browse files
committed
Refactor: extract annotation retrieval and improve typing for Python 3.9 compatibility
1 parent 164a45c commit 2ab78f3

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

src/dependency_injector/wiring.py

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -578,13 +578,12 @@ def _unpatch_attribute(patched: PatchedAttribute) -> None:
578578

579579

580580
def _extract_marker(parameter: inspect.Parameter) -> Optional["_Marker"]:
581-
is_annotated = (
582-
isinstance(annotation, type(Annotated))
583-
and get_origin(annotation) is not None
584-
and get_origin(annotation) is get_origin(Annotated)
585-
)
586-
if is_annotated:
587-
marker = get_args(annotation)[1]
581+
if get_origin(parameter.annotation) is Annotated:
582+
args = get_args(parameter.annotation)
583+
if len(args) > 1:
584+
marker = args[1]
585+
else:
586+
marker = None
588587
else:
589588
marker = parameter.default
590589

@@ -1032,19 +1031,18 @@ def _patched(*args, **kwargs):
10321031
return cast(F, _patched)
10331032

10341033

1034+
def _get_annotations(obj: Any) -> Dict[str, Any]:
1035+
if sys.version_info >= (3, 10):
1036+
return inspect.get_annotations(obj)
1037+
else:
1038+
return getattr(obj, "__annotations__", {})
1039+
1040+
10351041
def _get_members_and_annotated(obj: Any) -> Iterable[Tuple[str, Any]]:
10361042
members = inspect.getmembers(obj)
1037-
try:
1038-
annotations = inspect.get_annotations(obj)
1039-
except Exception:
1040-
annotations = {}
1043+
annotations = _get_annotations(obj)
10411044
for annotation_name, annotation in annotations.items():
1042-
is_annotated = (
1043-
isinstance(annotation, type(Annotated))
1044-
and get_origin(annotation) is not None
1045-
and get_origin(annotation) is get_origin(Annotated)
1046-
)
1047-
if is_annotated:
1045+
if get_origin(annotation) is Annotated:
10481046
args = get_args(annotation)
10491047
if len(args) > 1:
10501048
member = args[1]

0 commit comments

Comments
 (0)