Skip to content

Commit ee3bcbc

Browse files
committed
AnnotationFactory class delegating the construction to another factory
1 parent 5072dda commit ee3bcbc

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

named_annotations.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from abc import ABC, abstractmethod
2+
from typing import Iterable, Mapping, Final
23

34

45
class AnnotationFactory(ABC):
@@ -24,3 +25,64 @@ def _create_full_annotation_by(self, annotation: any) -> any:
2425
"""Annotation Creation Method from an input annotation."""
2526

2627

28+
class CustomAnnotationFactory(AnnotationFactory):
29+
"""
30+
AnnotationFactory class delegating the construction of another factory's
31+
annotation.
32+
33+
When called, replaces the 'annotation' strings from its arguments and their
34+
subcollections with the input annotation.
35+
"""
36+
37+
_input_annotation_annotation: str = '<input_annotation>'
38+
39+
def __init__(self, original_factory: Mapping, annotations: Iterable):
40+
self._original_factory = original_factory
41+
self._annotations = tuple(annotations)
42+
43+
@property
44+
def original_factory(self) -> Mapping:
45+
return self._original_factory
46+
47+
@property
48+
def annotations(self) -> tuple:
49+
return self._annotations
50+
51+
@classmethod
52+
@property
53+
def input_annotation_annotation(cls) -> str:
54+
return cls._input_annotation_annotation
55+
56+
def __repr__(self) -> str:
57+
return "{factory}{arguments}".format(
58+
factory=(
59+
self._original_factory.__name__
60+
if hasattr(self._original_factory, '__name__')
61+
else self._original_factory
62+
),
63+
arguments=str(self.__recursively_format(self._annotations)).replace('\'', str())
64+
)
65+
66+
def _create_full_annotation_by(self, annotation: any) -> any:
67+
return self._original_factory[
68+
*self.__get_formatted_annotations_from(self._annotations, annotation)
69+
]
70+
71+
def __recursively_format(self, collection: Iterable) -> list:
72+
"""
73+
Method for formatting the elements of a collection (and all of its
74+
sub-collections) as a list with possible element names or themselves.
75+
"""
76+
77+
formatted_collection = list()
78+
79+
for item in collection:
80+
if isinstance(item, Iterable) and not isinstance(item, str):
81+
formatted_collection.append(self.__recursively_format(item))
82+
elif hasattr(item, '__name__'):
83+
formatted_collection.append(item.__name__)
84+
else:
85+
formatted_collection.append(item)
86+
87+
return formatted_collection
88+

0 commit comments

Comments
 (0)