├── .gitignore ├── LICENSE ├── README.md ├── benchmark ├── classes.py ├── p_dishka.py ├── p_fastdi.py └── run.py ├── examples └── main.py ├── pyproject.toml ├── ruff.toml └── src └── fastdi ├── __init__.py ├── exceptions.py ├── graph ├── __init__.py ├── adjacent_dependencies.py ├── builders.py └── compilation.py ├── provider ├── __init__.py ├── parsers.py └── provider.py ├── py.typed └── resolver.py /.gitignore: -------------------------------------------------------------------------------- 1 | venv -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Фичи: 2 | * **Скоупы**. 3 | * **Финализация**. 4 | * **Модульные провайдеры**. 5 | * **Высокая скорость резолва зависимостей**. 6 | * **Максимально минималистичный апи**. Для работы со всеми возможностями fastdi требуется импортировать всего 2 сущности. 7 | 8 | ## Примеры использования 9 | 10 | Все зависимости fastdi, которые вам нужны это: 11 | 12 | ```python 13 | from fastdi import make_resolver, Provider 14 | ``` 15 | 16 | Теперь создадим несколько классов, которые будем собирать: 17 | 18 | ```python 19 | class Session: 20 | pass 21 | 22 | 23 | class DAO: 24 | 25 | def __init__(self, session: Session): 26 | pass 27 | 28 | 29 | class DomainService: 30 | 31 | def __init__(self, dao: DAO): 32 | pass 33 | 34 | 35 | class ApplicationService: 36 | 37 | def __init__(self, domain_service: DomainService, dao: DAO): 38 | pass 39 | ``` 40 | 41 | Далее нужно создать провайдер и предоставить ему фабрики с зависимостями. 42 | Так же необходимо обязательно указать скоуп, который отвечает за контроль жизненного цика созданного объекта: 43 | 44 | ```python 45 | from typing import Iterable 46 | 47 | 48 | provider = Provider() 49 | 50 | REQUEST_SCOPE = 'request' 51 | 52 | 53 | @provider.provide(scope=REQUEST_SCOPE) 54 | def session() -> Iterable[Session]: 55 | print('get session') 56 | yield Session() 57 | # здесь пишем код, ответственный за закрытие сессии, 58 | # он автоматически будет вызван после выхода из 59 | # соответствующего скоупа, в данном примере после 60 | # выхода из REQUEST_SCOPE 61 | print('close session') 62 | 63 | 64 | @provider.provide(scope=REQUEST_SCOPE) 65 | def dao(session: Session) -> DAO: 66 | return DAO(session=session) 67 | 68 | 69 | @provider.provide(scope=REQUEST_SCOPE) 70 | def domain_service(dao: DAO) -> DomainService: 71 | return DomainService(dao=dao) 72 | 73 | 74 | @provider.provide(scope=REQUEST_SCOPE) 75 | def application_service(domain_service: DomainService, dao: DAO) -> ApplicationService: 76 | return ApplicationService( 77 | domain_service=domain_service, 78 | dao=dao, 79 | ) 80 | ``` 81 | 82 | Остановимся немного на примере кода выше и на машинерии работы скоупов. Скоупы контролируют 83 | жизненный цик объекта, т.е. если объект задекларирован в скоупе **request** то 84 | сборку этого объекта можно будет запрашивать не ранее чем вы войдете в этот скуоп 85 | (дальнейшие пояснения в комментариях к коду): 86 | 87 | ```python 88 | # При создании контейнера, обязательно нужно указать 89 | # имя глобального скоупа, его часто называют application scope, 90 | # объекты принадлежащие этому скоупу никогда не будут уничтожены. 91 | resolver = make_resolver(provider, scope='app') 92 | 93 | # Вход в скоуп контролируется контекстными менеджерами, 94 | # благодаря им на момент выхода из скоупа, которому принадлежит 95 | # объект, он будет автоматически финализирован. 96 | 97 | # По умолчанию мы всегда находимся в глобальном скоупе, 98 | # войдем теперь в созданный нами выше REQUEST_SCOPE 99 | with resolver(scope=REQUEST_SCOPE) as request_resolver: 100 | # здесь мы можем попросить контейнер собрать объекты 101 | # принадлежащие этому или родительским скоупам, 102 | # соберем наш ApplicationService 103 | service = request_resolver.get(ApplicationService) 104 | print(service) 105 | 106 | # после выхода из данного контекста все принадлежащие ему 107 | # объекты будут финализированны, к примеру если запустить 108 | # этот код то по выходу из контекста REQUEST_SCOPE 109 | # вы увидите 'close session' 110 | ``` 111 | 112 | Важный момент относительно скоупов, в fastdi скоупы бесконечные, вы можете создавать сколько угодно скоупов 113 | и определять их иерархию контекстными менеджерами, т.е. родительский скоуп определяется порядком входа 114 | в соответствующие контексты. Имена скоупов определяются произвольными строками, вы вольны давать им любое имя: 115 | 116 | ```python 117 | # app scope -> request scope 118 | with resolver(scope='request') as request_resolver: 119 | # request scope -> interactor scope 120 | with request_resolver(scope='interactor') as interactor_resolver: 121 | # interator scope -> action scope 122 | with interactor_resolver(scope='action') as action_resolver: 123 | # и так до бесконечности, до любой вложенности скоупов, 124 | # которая вам необходима 125 | pass 126 | ``` -------------------------------------------------------------------------------- /benchmark/classes.py: -------------------------------------------------------------------------------- 1 | class CCCC: 2 | 3 | def __init__(self): 4 | pass 5 | 6 | 7 | class CCC: 8 | 9 | def __init__(self, c: CCCC): 10 | pass 11 | 12 | 13 | class CC: 14 | 15 | def __init__(self, c: CCC): 16 | pass 17 | 18 | 19 | class C: 20 | 21 | def __init__(self, c: CC): 22 | pass 23 | 24 | 25 | class BBBB: 26 | 27 | def __init__(self): 28 | pass 29 | 30 | 31 | class BBB: 32 | 33 | def __init__(self, b: BBBB): 34 | pass 35 | 36 | 37 | class BB: 38 | 39 | def __init__(self, b: BBB): 40 | pass 41 | 42 | 43 | class B: 44 | 45 | def __init__(self, b: BB): 46 | pass 47 | 48 | 49 | class DDDD: 50 | 51 | def __init__(self): 52 | pass 53 | 54 | 55 | class DDD: 56 | 57 | def __init__(self, d: DDDD): 58 | pass 59 | 60 | 61 | class DD: 62 | 63 | def __init__(self, d: DDD): 64 | pass 65 | 66 | 67 | class D: 68 | 69 | def __init__(self, d: DD): 70 | pass 71 | 72 | 73 | class A: 74 | 75 | def __init__(self, b: B, c: C, d: D): 76 | pass 77 | -------------------------------------------------------------------------------- /benchmark/p_dishka.py: -------------------------------------------------------------------------------- 1 | from classes import ( 2 | BB, 3 | BBB, 4 | BBBB, 5 | CC, 6 | CCC, 7 | CCCC, 8 | DD, 9 | DDD, 10 | DDDD, 11 | A, 12 | B, 13 | C, 14 | D, 15 | ) 16 | from dishka import Provider, Scope, make_container 17 | 18 | provider = Provider(scope=Scope.REQUEST) 19 | 20 | provider.provide(CCCC) 21 | provider.provide(CCC) 22 | provider.provide(CC) 23 | provider.provide(C) 24 | provider.provide(DDDD) 25 | provider.provide(DDD) 26 | provider.provide(DD) 27 | provider.provide(D) 28 | provider.provide(BBBB) 29 | provider.provide(BBB) 30 | provider.provide(BB) 31 | provider.provide(B) 32 | provider.provide(A) 33 | 34 | container = make_container(provider) 35 | -------------------------------------------------------------------------------- /benchmark/p_fastdi.py: -------------------------------------------------------------------------------- 1 | from classes import ( 2 | BB, 3 | BBB, 4 | BBBB, 5 | CC, 6 | CCC, 7 | CCCC, 8 | DD, 9 | DDD, 10 | DDDD, 11 | A, 12 | B, 13 | C, 14 | D, 15 | ) 16 | 17 | from fastdi import Provider, make_resolver 18 | 19 | REQUEST_SCOPE = 'request' 20 | APP_SCOPE = 'app' 21 | 22 | provider = Provider(scope=REQUEST_SCOPE) 23 | 24 | provider.provide(A) 25 | provider.provide(B) 26 | provider.provide(BB) 27 | provider.provide(BBB) 28 | provider.provide(BBBB) 29 | provider.provide(C) 30 | provider.provide(CC) 31 | provider.provide(CCC) 32 | provider.provide(CCCC) 33 | provider.provide(D) 34 | provider.provide(DD) 35 | provider.provide(DDD) 36 | provider.provide(DDDD) 37 | 38 | resolver = make_resolver(provider, scope=APP_SCOPE) 39 | -------------------------------------------------------------------------------- /benchmark/run.py: -------------------------------------------------------------------------------- 1 | import timeit 2 | 3 | from classes import A 4 | from p_fastdi import resolver, REQUEST_SCOPE 5 | from p_dishka import container, Scope 6 | 7 | 8 | print('dishka: ', timeit.timeit('with container(scope=Scope.REQUEST) as request_container: request_container.get(A)', globals=locals())) 9 | print('fastdi: ', timeit.timeit('with resolver(scope=REQUEST_SCOPE) as request_resolver: request_resolver.get(A)', globals=locals())) 10 | -------------------------------------------------------------------------------- /examples/main.py: -------------------------------------------------------------------------------- 1 | from fastdi import make_resolver, Provider 2 | 3 | from typing import Iterable 4 | 5 | 6 | class Session: 7 | pass 8 | 9 | 10 | class DAO: 11 | 12 | def __init__(self, session: Session): 13 | pass 14 | 15 | 16 | class DomainService: 17 | 18 | def __init__(self, dao: DAO): 19 | pass 20 | 21 | 22 | class ApplicationService: 23 | 24 | def __init__(self, domain_service: DomainService, dao: DAO): 25 | pass 26 | 27 | 28 | provider = Provider() 29 | 30 | REQUEST_SCOPE = 'request' 31 | 32 | 33 | @provider.provide(scope=REQUEST_SCOPE) 34 | def session() -> Iterable[Session]: 35 | print('get session') 36 | yield Session() 37 | # здесь пишем код, ответственный за закрытие сессии, 38 | # он автоматически будет вызван после выхода из 39 | # соответствующего скоупа, в данном примере после 40 | # выхода из REQUEST_SCOPE 41 | print('close session') 42 | 43 | 44 | @provider.provide(scope=REQUEST_SCOPE) 45 | def dao(session: Session) -> DAO: 46 | return DAO(session=session) 47 | 48 | 49 | @provider.provide(scope=REQUEST_SCOPE) 50 | def domain_service(dao: DAO) -> DomainService: 51 | return DomainService(dao=dao) 52 | 53 | 54 | @provider.provide(scope=REQUEST_SCOPE) 55 | def application_service(domain_service: DomainService, dao: DAO) -> ApplicationService: 56 | return ApplicationService( 57 | domain_service=domain_service, 58 | dao=dao, 59 | ) 60 | 61 | 62 | # При создании контейнера, обязательно нужно указать 63 | # имя глобального скоупа, его часто называют application scoupe, 64 | # объекты принадлежащие этому скоупу никогда не будут уничтожены. 65 | resolver = make_resolver(provider, scope='app') 66 | 67 | # Вход в скоуп контролируется контекстными менеджерами, 68 | # благодаря им на момент выхода из скоупа, которому принадлежит 69 | # объект, он будет автоматически финализирован. 70 | 71 | # По умолчанию мы всегда находимся в глобальном скоупе, 72 | # войдем теперь в созданный нами выше REQUEST_SCOPE 73 | with resolver(scope=REQUEST_SCOPE) as request_resolver: 74 | # здесь мы можем попросить контейнер собрать объекты 75 | # принадлежащие этому или родительским скоупам, 76 | # соберем наш ApplicationService 77 | service = request_resolver.get(ApplicationService) 78 | print(service) 79 | 80 | # после выхода из данного контекста все принадлежащие ему 81 | # объекты будут финализированны, к примеру если запустить 82 | # этот код то по выходу из контекста REQUEST_SCOPE 83 | # вы увидите 'close session' 84 | 85 | 86 | # app scope -> request scope 87 | with resolver(scope='request') as request_resolver: 88 | # request scope -> interactor scope 89 | with request_resolver(scope='interactor') as interactor_resolver: 90 | # interator scoue -> action scope 91 | with interactor_resolver(scope='action') as action_resolver: 92 | # и так до бесконечности, до любой вложенности скоупов, 93 | # которая вам необходима 94 | pass -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [tool.setuptools] 6 | include-package-data = true 7 | 8 | [tool.setuptools.packages.find] 9 | where = ["src"] 10 | 11 | [project] 12 | name = "fastdi" 13 | version = "0.0.1" 14 | authors = [ 15 | { name = "Igor Gritsenko", email = "igoryuha.g@gmail.com" }, 16 | ] 17 | license = { text = "Apache-2.0" } 18 | classifiers = [ 19 | "Programming Language :: Python :: 3.10", 20 | "License :: OSI Approved :: Apache Software License", 21 | "Operating System :: OS Independent", 22 | ] 23 | 24 | [project.optional-dependencies] 25 | dev = [ 26 | "mypy", 27 | "ruff", 28 | ] 29 | 30 | [project.urls] 31 | Homepage = "https://github.com/igoryuha/fastdi" -------------------------------------------------------------------------------- /ruff.toml: -------------------------------------------------------------------------------- 1 | target-version = "py310" 2 | line-length = 79 3 | 4 | include = ["src/**/*.py"] 5 | 6 | [lint] 7 | select = [ 8 | "A", 9 | "B", 10 | "E", 11 | "F", 12 | "UP", 13 | "B", 14 | "SIM", 15 | "I", 16 | "C4", 17 | "T20", 18 | "COM", 19 | "ISC", 20 | "W", 21 | "PT", 22 | "RSE", 23 | "SLF", 24 | "SLOT", 25 | "PTH", 26 | ] 27 | 28 | ignore = [ 29 | "SIM105", 30 | ] 31 | -------------------------------------------------------------------------------- /src/fastdi/__init__.py: -------------------------------------------------------------------------------- 1 | from .provider import Provider 2 | from .resolver import make_resolver 3 | 4 | __all__ = [ 5 | "make_resolver", 6 | "Provider", 7 | ] 8 | -------------------------------------------------------------------------------- /src/fastdi/exceptions.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/igoryuha/fastdi/3e6fa4f3bbfe76439e578fdb5731650e27efe935/src/fastdi/exceptions.py -------------------------------------------------------------------------------- /src/fastdi/graph/__init__.py: -------------------------------------------------------------------------------- 1 | from .adjacent_dependencies import AdjacentDependencies 2 | from .builders import ( 3 | build_adj_deps_from_class, 4 | build_adj_deps_from_factory, 5 | ) 6 | 7 | __all__ = [ 8 | "AdjacentDependencies", 9 | "build_adj_deps_from_class", 10 | "build_adj_deps_from_factory", 11 | ] 12 | -------------------------------------------------------------------------------- /src/fastdi/graph/adjacent_dependencies.py: -------------------------------------------------------------------------------- 1 | from .compilation import Resolve 2 | 3 | 4 | class AdjacentDependencies: 5 | 6 | __slots__ = ( 7 | "resolve", 8 | "key_type_scope", 9 | ) 10 | 11 | def __init__( 12 | self, 13 | resolve: Resolve, 14 | key_type_scope: str, 15 | ): 16 | self.resolve = resolve 17 | self.key_type_scope = key_type_scope 18 | -------------------------------------------------------------------------------- /src/fastdi/graph/builders.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Callable 2 | from typing import Any 3 | 4 | from .adjacent_dependencies import AdjacentDependencies 5 | from .compilation import ( 6 | compile_resolve_from_function, 7 | compile_resolve_frome_class, 8 | ) 9 | 10 | 11 | def build_adj_deps_from_class( 12 | origin: type, 13 | scope: str, 14 | depends: dict[str, Any], 15 | with_cache: bool = True, 16 | ) -> AdjacentDependencies: 17 | resolve = compile_resolve_frome_class( 18 | origin=origin, 19 | vars_for_resolve=depends, 20 | with_cache=with_cache, 21 | ) 22 | return AdjacentDependencies( 23 | resolve=resolve, 24 | key_type_scope=scope, 25 | ) 26 | 27 | 28 | def build_adj_deps_from_factory( 29 | factory: Callable[..., Any], 30 | scope: str, 31 | depends: dict[str, Any], 32 | key_type: Any, 33 | with_cache: bool = True, 34 | ) -> AdjacentDependencies: 35 | resolve = compile_resolve_from_function( 36 | factory=factory, 37 | vars_for_resolve=depends, 38 | key_type=key_type, 39 | with_cache=with_cache, 40 | ) 41 | return AdjacentDependencies( 42 | resolve=resolve, 43 | key_type_scope=scope, 44 | ) 45 | -------------------------------------------------------------------------------- /src/fastdi/graph/compilation.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Callable, Generator 2 | from inspect import isfunction, isgeneratorfunction 3 | from typing import Any, get_args 4 | 5 | Exits = list[Generator] 6 | Cache = dict[Any, Any] 7 | Get = Callable[[Any], Any] 8 | 9 | Resolve = Callable[[Get, Cache, Exits], Any] 10 | 11 | FN_TEMPLATE = """ 12 | def resolve(get, cache, exits): 13 | solved = origin({args}) 14 | {cache} 15 | return solved 16 | """ 17 | 18 | GEN_TEMPLATE = """ 19 | def resolve(get, cache, exits): 20 | gen = origin({args}) 21 | solved = gen.send(None) 22 | {cache} 23 | exits.append(gen) 24 | return solved 25 | """ 26 | 27 | CACHE = "cache[key_type] = solved" 28 | 29 | 30 | def make_args(vars_for_resolve: dict[str, Any]) -> str: 31 | r_ = [] 32 | for varname in vars_for_resolve: 33 | r_.append(f'get({varname})') 34 | return ', '.join(r_) 35 | 36 | 37 | def compile_resolve_frome_class( 38 | origin: type, 39 | vars_for_resolve: dict[str, Any], 40 | with_cache: bool = True, 41 | ) -> Resolve: 42 | return compile_resolve( 43 | origin=origin, 44 | key_type=origin, 45 | vars_for_resolve=vars_for_resolve, 46 | body_template=FN_TEMPLATE, 47 | with_cache=with_cache, 48 | ) 49 | 50 | 51 | def compile_resolve_from_function( 52 | factory: Callable[..., Any], 53 | vars_for_resolve: dict[str, Any], 54 | key_type: Any, 55 | with_cache: bool = True, 56 | ) -> Resolve: 57 | if isgeneratorfunction(factory): 58 | key_type, = get_args(key_type) 59 | body_template = GEN_TEMPLATE 60 | elif isfunction(factory): 61 | body_template = FN_TEMPLATE 62 | 63 | return compile_resolve( 64 | origin=factory, 65 | key_type=key_type, 66 | vars_for_resolve=vars_for_resolve, 67 | body_template=body_template, 68 | with_cache=with_cache, 69 | ) 70 | 71 | 72 | def compile_resolve( 73 | origin: Callable[..., Any], 74 | key_type: Any, 75 | vars_for_resolve: dict[str, Any], 76 | body_template: str, 77 | with_cache = True, 78 | ) -> Resolve: 79 | cache = CACHE if with_cache else '' 80 | args = make_args(vars_for_resolve) 81 | 82 | global_vars = { 83 | 'origin': origin, 84 | 'key_type': key_type, 85 | **vars_for_resolve, 86 | } 87 | body = body_template.format_map({ 88 | 'args': args, 89 | 'cache': cache, 90 | }) 91 | compiled = compile(body, '', 'exec') 92 | exec(compiled, global_vars) 93 | 94 | return global_vars['resolve'] 95 | -------------------------------------------------------------------------------- /src/fastdi/provider/__init__.py: -------------------------------------------------------------------------------- 1 | from .provider import Provider 2 | 3 | __all__ = [ 4 | "Provider", 5 | ] 6 | -------------------------------------------------------------------------------- /src/fastdi/provider/parsers.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Callable 2 | from inspect import signature 3 | from typing import Any 4 | 5 | 6 | def parse_class_signature( 7 | origin: type, 8 | ) -> tuple[Any, dict[str, Any]]: 9 | init_signature = signature(origin.__init__) # type: ignore 10 | 11 | depends = {} 12 | for k, v in init_signature.parameters.items(): 13 | if k == 'self': 14 | continue 15 | depends[k] = v.annotation 16 | 17 | return origin, depends 18 | 19 | 20 | def parse_function_signature( 21 | factory: Callable[..., Any], 22 | ) -> tuple[Any, dict[str, Any]]: 23 | factory_signature = signature(factory) 24 | 25 | depends = {} 26 | for k, v in factory_signature.parameters.items(): 27 | depends[k] = v.annotation 28 | 29 | return factory_signature.return_annotation, depends 30 | -------------------------------------------------------------------------------- /src/fastdi/provider/provider.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Callable 2 | from inspect import isclass, isfunction 3 | from typing import Any 4 | 5 | from fastdi.graph import ( 6 | AdjacentDependencies, 7 | build_adj_deps_from_class, 8 | build_adj_deps_from_factory, 9 | ) 10 | 11 | from .parsers import ( 12 | parse_class_signature, 13 | parse_function_signature, 14 | ) 15 | 16 | Graph = dict[Any, AdjacentDependencies] 17 | 18 | 19 | class Provider: 20 | 21 | def __init__(self, scope: str | None = None): 22 | self.graph: Graph = {} 23 | self.scope = scope 24 | 25 | def provide( 26 | self, 27 | origin: Callable[..., Any] | None = None, 28 | *, 29 | scope: str | None = None, 30 | cache: bool = True, 31 | ): 32 | scope = scope if scope else self.scope 33 | if not scope: 34 | raise RuntimeError 35 | 36 | if origin: 37 | if isclass(origin): 38 | return self._register_class( 39 | origin=origin, 40 | scope=scope, 41 | cache=cache, 42 | ) 43 | elif isfunction(origin): 44 | return self._register_factory( 45 | provider=origin, 46 | scope=scope, 47 | cache=cache, 48 | ) 49 | 50 | def inner(provider): 51 | return self._register_factory( 52 | provider=provider, 53 | scope=scope, 54 | cache=cache, 55 | ) 56 | return inner 57 | 58 | def _register_class( 59 | self, 60 | origin: type, 61 | scope: str, 62 | cache: bool, 63 | ): 64 | key_type, depends = parse_class_signature(origin) 65 | 66 | adjacent_dependencies = build_adj_deps_from_class( 67 | origin=origin, 68 | scope=scope, 69 | depends=depends, 70 | with_cache=cache, 71 | ) 72 | self.graph[key_type] = adjacent_dependencies 73 | 74 | def _register_factory( 75 | self, 76 | provider: Callable[..., Any], 77 | scope: str, 78 | cache: bool, 79 | ): 80 | key_type, depends = parse_function_signature(provider) 81 | 82 | adjacent_dependencies = build_adj_deps_from_factory( 83 | factory=provider, 84 | scope=scope, 85 | depends=depends, 86 | key_type=key_type, 87 | with_cache=cache, 88 | ) 89 | self.graph[key_type] = adjacent_dependencies 90 | 91 | return provider 92 | -------------------------------------------------------------------------------- /src/fastdi/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/igoryuha/fastdi/3e6fa4f3bbfe76439e578fdb5731650e27efe935/src/fastdi/py.typed -------------------------------------------------------------------------------- /src/fastdi/resolver.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from collections.abc import Generator 4 | from typing import Any 5 | 6 | from .graph import AdjacentDependencies 7 | from .provider import Provider 8 | 9 | 10 | class Resolver: 11 | 12 | __slots__ = ( 13 | "graph", 14 | "cache", 15 | "exits", 16 | "scope", 17 | "parent", 18 | ) 19 | 20 | def __init__( 21 | self, 22 | graph: dict[Any, AdjacentDependencies], 23 | scope: str, 24 | parent: Resolver | None = None, 25 | ): 26 | self.graph = graph 27 | self.scope = scope 28 | self.parent = parent 29 | self.cache: dict[Any, Any] = {} 30 | self.exits: list[Generator] = [] 31 | 32 | def get(self, key_type: Any) -> Any: 33 | if key_type in self.cache: 34 | return self.cache.get(key_type) 35 | 36 | try: 37 | adjacent_deps = self.graph[key_type] 38 | except KeyError as e: 39 | raise ValueError from e 40 | 41 | if self.scope != adjacent_deps.key_type_scope: 42 | try: 43 | return self.parent.get(key_type) # type: ignore[union-attr] 44 | except AttributeError as e: 45 | raise ValueError from e 46 | 47 | return adjacent_deps.resolve(self.get, self.cache, self.exits) 48 | 49 | def close(self): 50 | self.cache = {} 51 | for _exit in self.exits: 52 | try: 53 | _exit.send(None) 54 | except StopIteration: 55 | pass 56 | 57 | def __call__(self, scope: str): 58 | resolver = Resolver( 59 | graph=self.graph, 60 | scope=scope, 61 | parent=self, 62 | ) 63 | return ScopeContext(resolver) 64 | 65 | 66 | class ScopeContext: 67 | 68 | __slots__ = ( 69 | "resolver", 70 | ) 71 | 72 | def __init__(self, resolver): 73 | self.resolver = resolver 74 | 75 | def __enter__(self): 76 | return self.resolver 77 | 78 | def __exit__(self, exc_type, exc_value, traceback): 79 | self.resolver.close() 80 | 81 | 82 | def make_resolver(*providers: Provider, scope: str) -> Resolver: 83 | graph = {} 84 | for provider in providers: 85 | graph.update(provider.graph) 86 | 87 | return Resolver(graph=graph, scope=scope) 88 | --------------------------------------------------------------------------------