Wrapper for an exported factory. The wrapper manages the instance creation using the wrapped factory by calling the factory on the first requirement. The created instance is stored in a singleton manner and returned on further requirements. The export also manages the regi
| 20 | |
| 21 | |
| 22 | class Export(object): |
| 23 | ''' Wrapper for an exported factory. |
| 24 | |
| 25 | The wrapper manages the instance creation using the wrapped factory by |
| 26 | calling the factory on the first requirement. The created instance is |
| 27 | stored in a singleton manner and returned on further requirements. |
| 28 | |
| 29 | The export also manages the registered extends for the factory. These |
| 30 | extends are called after instance creation to manipulate the instance. |
| 31 | ''' |
| 32 | |
| 33 | def __init__(self, factory): |
| 34 | self.__factory = factory |
| 35 | self.__extends = [] |
| 36 | |
| 37 | self.__instance = None |
| 38 | |
| 39 | |
| 40 | def extend(self, extend): |
| 41 | ''' Extends this export. |
| 42 | |
| 43 | The instance created by the wrapped factory is extended by passing the |
| 44 | created instance to the given extend function after creation. |
| 45 | |
| 46 | The extend function must accept the instance as its only argument. If |
| 47 | the function returns a value which is not None, the instance is replaced |
| 48 | with the returned value. |
| 49 | ''' |
| 50 | |
| 51 | assert self.__instance is None |
| 52 | |
| 53 | self.__extends.append(extend) |
| 54 | |
| 55 | |
| 56 | @property |
| 57 | def instance(self): |
| 58 | ''' Returns the instance. |
| 59 | |
| 60 | If no instance exists, it is created as described above. |
| 61 | ''' |
| 62 | |
| 63 | # Create an instance none is available |
| 64 | if self.__instance is None: |
| 65 | |
| 66 | # Lazily create the instance by calling the factory |
| 67 | instance = self.__factory() |
| 68 | |
| 69 | # Call all extends for this export to update or replace the instance |
| 70 | for extend in self.__extends: |
| 71 | instance = extend(instance) or instance |
| 72 | |
| 73 | # Remember the instance for further requisition |
| 74 | self.__instance = instance |
| 75 | |
| 76 | return self.__instance |
| 77 | |
| 78 | |
| 79 | @staticmethod |