pax_global_header00006660000000000000000000000064150252316740014517gustar00rootroot0000000000000052 comment=6ff646bf566c83fb30c5b24fc6fe3b55bbb285f2 python-inject-5.3.0/000077500000000000000000000000001502523167400143175ustar00rootroot00000000000000python-inject-5.3.0/.gitignore000066400000000000000000000012631502523167400163110ustar00rootroot00000000000000# Intellij Idea .idea/ *.iml .vscode/ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] .mypy_cache/ # C extensions *.so # Distribution / packaging .Python env/ bin/ build/ develop-eggs/ dist/ eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports .tox/ .coverage .cache nosetests.xml coverage.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Rope .ropeproject # Django stuff: *.log *.pot # Sphinx documentation docs/_build/ # macOS files .DS_Store # pyenv virtualenv .python-version # Generated files _version.py _version.pyi python-inject-5.3.0/.travis.yml000066400000000000000000000004671502523167400164370ustar00rootroot00000000000000dist: xenial language: python matrix: include: - python: '3.6' - python: '3.7' env: TOXENV=py37 - python: '3.8' env: TOXENV=py37 install: - python -m pip install --upgrade --editable=./ script: - nosetests test $EXTRA_ARGS - if [ "$TOXENV" = "py37" ]; then nosetests test37; fi python-inject-5.3.0/CHANGES.md000066400000000000000000000055011502523167400157120ustar00rootroot00000000000000python-inject changes ===================== ### 5.3.0 (2025-06-20) - Handle autoparams usage without braces, #115. ### 5.2.1 (2024-03-24) - Remove type stubs as source has type hints, #95. - Added context manager condition to attr function, #96, #94. ### 5.2.0 (2023-11-23) - Context managers support. ### 5.1.0 (2023-10-17) - Optionally allow overriding dependencies. - Unified configure syntax with clear and once flags. ### 5.0.0 (2023-06-10) - Support for PEP0604 for Python>=3.10. ### 4.3.1 (2020-08-17) - Use assertRaisesRegex instead of assertRaisesRegexp to fix deprecation warnings. ### 4.3.0 (2020-08-11) - Support for classes in autoparams, #59. - Support for asyncio, #66. ### 4.2.0 (2020-05-15) - Migrated autoparams and annotations to typing.get_type_hints. - Fix boolean casting to make possible to inject DataFrame (#55) #56. - Add support for forward references #54. ### 4.1.2 (2020-04-13) - Include py.typed and manifest in dist, #50. ### 4.1.1 (2020-02-25) - UTF8 encoding for readme in setup.py, #48. ### 4.1.0 (2020-02-24) - More precise typing #47. - Removed Python 3.5 support. ### 4.0.0 (2019-11-25) - Drop Python <3.5 support. - [feature] Add typed information, #43. - [chore] Remov old typing information as it is no longer relevant for v4.0.0, #43. ### 3.5.4 (2019-07-30) - MyPy compatibility #36. ### 3.5.3 (2019-07-24) - AttributeError: type object 'Callable' has no attribute '_abc_registry' #34 ### 3.5.2 (2019-07-10) - Modify type-hints to support Hashable bindings and other improvements, #33. - Merge these type-hints into the .py file instead of having a .pyi file, #33. ### 3.5.1 (2019-04-16) - Export Binder and Injector in pyi, #29. - Make autoparams work with keyword-only parameters, #26. ### 3.5.0 (2019-03-11) - Configurable auto-initialization, #23 [@Fedorof](https://github.com/Fedorof). ### 3.4.0 (2018-08-01) - Type hinting in Python 3, #20 [@Enforcer](https://github.com/Enforcer). - Autoparams leveraging types annotations, #21 [@Enforcer](https://github.com/Enforcer). ### 3.3.2 (2017-09-14) - Use getfullargspec when executing in Python3, #17 [@jaimewyant](https://github.com/jaimewyant). ### 3.3.1 (2015-03-28) - Fixed race condition in bind_to_constructor, #14 [@peick](https://github.com/peick). ### 3.3.0 (2014-08-22) - Added `inject.params(arg1=cls1, arg2=cls2)`, deprecated `inject.param`, #12 (thanks [@scharf](https://github.com/scharf)). ### 3.2.0 (2014-08-04) - Added `inject.configure_once` and `inject.is_configured`, #11. ### 3.1.1 (2014-03-14) - Switch from root logger to module logger, #8. ### 3.1.0 (2014-03-07) - `inject.param` decorator. - Small fixes in exceptions. ### 3.0.0 (2014-02-10) - Smaller, better, faster version with simpler and cleaner API. ### 2.0.0-alpha1 (2010-08-25) - Second version (never made it to stable). ### 1.0.0 (2010-02-12) - Initial release. python-inject-5.3.0/LICENSE000066400000000000000000000261361502523167400153340ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. python-inject-5.3.0/MANIFEST.in000066400000000000000000000001351502523167400160540ustar00rootroot00000000000000include CHANGES.md include LICENSE include README.md recursive-include inject *.py py.typed python-inject-5.3.0/README.md000066400000000000000000000227711502523167400156070ustar00rootroot00000000000000# python-inject [![Build Status](https://travis-ci.org/ivankorobkov/python-inject.svg?branch=master)](https://travis-ci.org/ivankorobkov/python-inject) Dependency injection the python way, the good way. ## Key features * Fast. * Thread-safe. * Simple to use. * Does not steal class constructors. * Does not try to manage your application object graph. * Transparently integrates into tests. * Autoparams leveraging type annotations. * Supports type hinting in Python 3.5+. * Supports Python 3.9+ (`v5.*`), 3.5-3.8 (`v4.*`) and Python 2.7–3.5 (`v3.*`). * Supports context managers. ## Python Support | Python | Inject Version | |---------|----------------| | 3.9+ | 5.0+ | | 3.6-3.8 | 4.1+, < 5.0 | | 3.5 | 4.0 | | < 3.5 | 3.* | ## Installation Use pip to install the lastest version: ```bash pip install inject ``` ## Autoparams example `@inject.autoparams` returns a decorator which automatically injects arguments into a function that uses type annotations. This is supported only in Python >= 3.5. ```python @inject.autoparams def refresh_cache(cache: RedisCache, db: DbInterface): pass ``` There is an option to specify which arguments we want to inject without attempts of injecting everything: ```python @inject.autoparams('cache', 'db') def sign_up(name, email, cache: RedisCache, db: DbInterface): pass ``` It is also acceptable to use explicit curly braces notation (`@inject.autoparams()`) for non-parameterized decorations — it will be treated the same as `@inject.autoparams`. ## Step-by-step example ```python # Import the inject module. import inject # `inject.instance` requests dependencies from the injector. def foo(bar): cache = inject.instance(Cache) cache.save('bar', bar) # `inject.params` injects dependencies as keyword arguments or positional argument. # Also you can use @inject.autoparams in Python 3.5, see the example above. @inject.params(cache=Cache, user=CurrentUser) def baz(foo, cache=None, user=None): cache.save('foo', foo, user) # this can be called in different ways: # with injected arguments baz('foo') # with positional arguments baz('foo', my_cache) # with keyword arguments baz('foo', my_cache, user=current_user) # `inject.param` is deprecated, use `inject.params` instead. @inject.param('cache', Cache) def bar(foo, cache=None): cache.save('foo', foo) # `inject.attr` creates properties (descriptors) which request dependencies on access. class User(object): cache = inject.attr(Cache) def __init__(self, id): self.id = id def save(self): self.cache.save('users', self) @classmethod def load(cls, id): return cls.cache.load('users', id) # Create an optional configuration. def my_config(binder): binder.bind(Cache, RedisCache('localhost:1234')) # Configure a shared injector. inject.configure(my_config) # Instantiate User as a normal class. Its `cache` dependency is injected when accessed. user = User(10) user.save() # Call the functions, the dependencies are automatically injected. foo('Hello') bar('world') ``` ## Context managers Binding a class to an instance of a context manager (through `bind` or `bind_to_constructor`) or to a function decorated as a context manager leads to the context manager to be used as is, not via with statement. ```python @contextlib.contextmanager def get_file_sync(): obj = MockFile() yield obj obj.destroy() @contextlib.asynccontextmanager async def get_conn_async(): obj = MockConnection() yield obj obj.destroy() def config(binder): binder.bind_to_provider(MockFile, get_file_sync) binder.bind(int, 100) binder.bind_to_provider(str, lambda: "Hello") binder.bind_to_provider(MockConnection, get_conn_sync) inject.configure(config) @inject.autoparams() def example(conn: MockConnection, file: MockFile): # Connection and file will be automatically destroyed on exit. pass ``` ## Usage with Django Django can load some modules multiple times which can lead to `InjectorException: Injector is already configured`. You can use `configure(once=True)` which is guaranteed to run only once when the injector is absent: ```python import inject inject.configure(my_config, once=True) ``` ## Testing In tests use `inject.configure(callable, clear=True)` to create a new injector on setup, and optionally `inject.clear()` to clean up on tear down: ```python class MyTest(unittest.TestCase): def setUp(self): inject.configure(lambda binder: binder .bind(Cache, MockCache()) \ .bind(Validator, TestValidator()), clear=True) def tearDown(self): inject.clear() ``` ## Composable configurations You can reuse configurations and override already registered dependencies to fit the needs in different environments or specific tests. ```python def base_config(binder): # ... more dependencies registered here binder.bind(Validator, RealValidator()) binder.bind(Cache, RedisCache('localhost:1234')) def tests_config(binder): # reuse existing configuration binder.install(base_config) # override only certain dependencies binder.bind(Validator, TestValidator()) binder.bind(Cache, MockCache()) inject.configure(tests_config, allow_override=True, clear=True) ``` ## Thread-safety After configuration the injector is thread-safe and can be safely reused by multiple threads. ## Binding types **Instance** bindings always return the same instance: ```python redis = RedisCache(address='localhost:1234') def config(binder): binder.bind(Cache, redis) ``` **Constructor** bindings create a singleton on injection: ```python def config(binder): # Creates a redis cache singleton on first injection. binder.bind_to_constructor(Cache, lambda: RedisCache(address='localhost:1234')) ``` **Provider** bindings call the provider on injection: ```python def get_my_thread_local_cache(): pass def config(binder): # Executes the provider on each injection. binder.bind_to_provider(Cache, get_my_thread_local_cache) ``` **Runtime** bindings automatically create singletons on injection, require no configuration. For example, only the `Config` class binding is present, other bindings are runtime: ```python class Config(object): pass class Cache(object): config = inject.attr(Config) class Db(object): config = inject.attr(Config) class User(object): cache = inject.attr(Cache) db = inject.attr(Db) @classmethod def load(cls, user_id): return cls.cache.load('users', user_id) or cls.db.load('users', user_id) inject.configure(lambda binder: binder.bind(Config, load_config_file())) user = User.load(10) ``` ## Disabling runtime binding Sometimes runtime binding leads to unexpected behaviour. Say if you forget to bind an instance to a class, `inject` will try to implicitly instantiate it. If an instance is unintentionally created with default arguments it may lead to hard-to-debug bugs. To disable runtime binding and make sure that only explicitly bound instances are injected, pass `bind_in_runtime=False` to `inject.configure`. In this case `inject` immediately raises `InjectorException` when the code tries to get an unbound instance. ## Keys It is possible to use any hashable object as a binding key. For example: ```python import inject inject.configure(lambda binder: \ binder.bind('host', 'localhost') \ binder.bind('port', 1234)) ``` ## Why no scopes? I've used Guice and Spring in Java for a lot of years, and I don't like their scopes. `python-inject` by default creates objects as singletons. It does not need a prototype scope as in Spring or NO_SCOPE as in Guice because `python-inject` does not steal your class constructors. Create instances the way you like and then inject dependencies into them. Other scopes such as a request scope or a session scope are fragile, introduce high coupling, and are difficult to test. In `python-inject` write custom providers which can be thread-local, request-local, etc. For example, a thread-local current user provider: ```python import inject import threading # Given a user class. class User(object): pass # Create a thread-local current user storage. _LOCAL = threading.local() def get_current_user(): return getattr(_LOCAL, 'user', None) def set_current_user(user): _LOCAL.user = user # Bind User to a custom provider. inject.configure(lambda binder: binder.bind_to_provider(User, get_current_user)) # Inject the current user. @inject.params(user=User) def foo(user): pass ``` ## Links * Project: https://github.com/ivankorobkov/python-inject ## License Apache License 2.0 ## Contributors * Ivan Korobkov [@ivankorobkov](https://github.com/ivankorobkov) * Jaime Wyant [@jaimewyant](https://github.com/jaimewyant) * Sebastian Buczyński [@Enforcer](https://github.com/Enforcer) * Oleksandr Fedorov [@Fedorof](https://github.com/Fedorof) * cselvaraj [@cselvaraj](https://github.com/cselvaraj) * 陆雨晴 [@SixExtreme](https://github.com/SixExtreme) * Andrew William Borba [@andrewborba10](https://github.com/andrewborba10) * jdmeyer3 [@jdmeyer3](https://github.com/jdmeyer3) * Alex Grover [@ajgrover](https://github.com/ajgrover) * Harro van der Kroft [@wisepotato](https://github.com/wisepotato) * Samiur Rahman [@samiur](https://github.com/samiur) * 45deg [@45deg](https://github.com/45deg) * Alexander Nicholas Costas [@ancostas](https://github.com/ancostas) * Dmitry Balabka [@dbalabka](https://github.com/dbalabka) * Dima Burmistrov [@pyctrl](https://github.com/pyctrl) python-inject-5.3.0/makefile000066400000000000000000000015671502523167400160300ustar00rootroot00000000000000SHELL := bash .DELETE_ON_ERROR: .SHELLFLAGS := -ceu MAKEFLAGS += --no-builtin-rules \ --warn-undefined-variables .PHONY: dist pytest test dist: if ! python3 -m pip freeze | grep -q build; then python3 -m pip install --upgrade build; fi python3 -m build --outdir=dist --sdist --wheel ./ install_dev: python3 -m pip install --upgrade pip python3 -m pip install --upgrade --editable=./ upload: if ! python3 -m pip freeze | grep -q twine; then python3 -m pip install --upgrade twine; fi python3 -m twine upload dist/* clean: rm -rf ./build/* rm -rf ./dist/* rm -rf ./.mypy_cache rm -rf ./.pytest_cache pytest: if ! command -v pytest &>/dev/null; then python3 -m pip install --upgrade pytest; fi pytest test test: if ! command -v nosetests &>/dev/null; then python3 -m pip install --upgrade nose; fi nosetests test python-inject-5.3.0/pyproject.toml000066400000000000000000000070401502523167400172340ustar00rootroot00000000000000[build-system] requires = ['hatchling', 'hatch-vcs'] build-backend = 'hatchling.build' [project] name = 'inject' dynamic = ['version'] description = 'Python dependency injection framework.' license = 'Apache-2.0' readme = 'README.md' authors = [{ name = 'Ivan Korobkov', email = 'ivan.korobkov@gmail.com' }] maintainers = [{ name = 'Ivan Korobkov', email = 'ivan.korobkov@gmail.com' }] classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Topic :: Software Development :: Libraries :: Python Modules', ] dependencies = [] [project.scripts] [project.urls] Homepage = 'https://github.com/ivankorobkov/python-inject' [tool.black] line-length = 120 skip-string-normalization = true target_version = ['py39', 'py310', 'py311'] include = '\.pyi?$' exclude = ''' /( \.eggs | \.git | \.github | \.hg | \.idea | \.mypy_cache | \.tox | \.pyre_configuration | \.venv | _build | build | dist | var ) ''' [tool.hatch.build.hooks.vcs] version-file = 'src/inject/_version.py' [tool.hatch.build.targets.wheel] packages = ['src/inject'] [tool.hatch.build.targets.wheel.shared-data] [tool.hatch.version] source = 'vcs' [tool.isort] case_sensitive = true include_trailing_comma = true line_length = 120 multi_line_output = 3 profile = 'black' [tool.mypy] check_untyped_defs = true disallow_any_generics = true disallow_incomplete_defs = true disallow_subclassing_any = true disallow_untyped_calls = true disallow_untyped_decorators = true disallow_untyped_defs = true ignore_missing_imports = true no_implicit_optional = true python_version = '3.11' warn_redundant_casts = true warn_return_any = true warn_unused_configs = true warn_unused_ignores = true [tool.pyright] defineConstant = { DEBUG = true } exclude = [] executionEnvironments = [] ignore = [] include = ['src/inject', 'test'] pythonPlatform = 'Linux' pythonVersion = '3.11' reportMissingImports = true reportMissingTypeStubs = false [tool.pytest.ini_options] addopts = '-rfEX --strict-markers --tb=long' minversion = '7.2' python_files = ['test_*.py'] testpaths = ['./test'] [tool.ruff] ignore = [ # Allow non-abstract empty methods in abstract base classes 'B027', # Allow boolean positional values in function calls, like `dict.get(... True)` 'FBT003', # Ignore checks for possible passwords 'S105', 'S106', 'S107', # Ignore complexity 'C901', 'PLR0911', 'PLR0912', 'PLR0913', 'PLR0915', 'PLC1901', # empty string comparisons 'PLW2901', # `for` loop variable overwritten 'SIM114', # Combine `if` branches using logical `or` operator ] line-length = 120 select = [ 'A', 'B', 'C', 'DTZ', 'E', 'EM', 'F', 'FBT', 'I', 'ICN', 'ISC', 'N', 'PLC', 'PLE', 'PLR', 'PLW', 'Q', 'RUF', 'S', 'SIM', 'T', 'TID', 'UP', 'W', 'YTT', ] target-version = ['py39', 'py310', 'py311'] unfixable = [ # Don't touch unused imports 'F401', ] [tool.ruff.flake8-quotes] inline-quotes = 'single' [tool.ruff.flake8-tidy-imports] ban-relative-imports = 'all' [tool.ruff.isort] known-first-party = ['inject'] [tool.ruff.per-file-ignores] # Tests can use magic values, assertions, and relative imports '/**/test_*.py' = ['PLR2004', 'S101', 'TID252'] python-inject-5.3.0/src/000077500000000000000000000000001502523167400151065ustar00rootroot00000000000000python-inject-5.3.0/src/inject/000077500000000000000000000000001502523167400163625ustar00rootroot00000000000000python-inject-5.3.0/src/inject/__init__.py000066400000000000000000000502221502523167400204740ustar00rootroot00000000000000""" Python dependency injection framework. Usage: - Create an optional configuration:: def my_config(binder): binder.bind(Cache, RedisCache('localhost:1234')) binder.bind_to_provider(CurrentUser, get_current_user) - Create a shared injector:: inject.configure(my_config) - Use `inject.instance`, `inject.attr` or `inject.param` to inject dependencies:: class User(object): cache = inject.attr(Cache) @classmethod def load(cls, id): return cls.cache.load('user', id) def save(self): self.cache.save(self) def foo(bar): cache = inject.instance(Cache) cache.save('bar', bar) @inject.params(cache=Cache) def bar(foo, cache=None): cache.save('foo', foo) Binding types: - Instance bindings configured via `bind(cls, instance) which always return the same instance. - Constructor bindings `bind_to_constructor(cls, callable)` which create a singleton on first access. - Provider bindings `bind_to_provider(cls, callable)` which call the provider for each injection. - Runtime bindings which automatically create class singletons. Thread-safety: After configuration the injector is thread-safe and can be safely reused by multiple threads. Unit testing: In tests use `inject.clear_and_configure(callable)` to create a new injector on setup, and `inject.clear()` to clean-up on tear down. Runtime bindings greatly reduce the required configuration by automatically creating singletons on first access. For example, below only the Config class requires binding configuration, all other classes are runtime bindings:: class Cache(object): config = inject.attr(Config) def __init__(self): self._redis = connect(self.config.redis_address) class Db(object): pass class UserRepo(object): cache = inject.attr(Cache) db = inject.attr(Db) def load(self, user_id): return cache.load('user', user_id) or db.load('user', user_id) class Config(object): def __init__(self, redis_address): self.redis_address = redis_address def my_config(binder): binder.bind(Config, load_config_file()) inject.configure(my_config) """ import contextlib from inject._version import __version__ import inspect import logging import sys import threading from functools import wraps from typing import (Any, Awaitable, Callable, Dict, Generic, Hashable, Optional, Set, Type, TypeVar, Union, cast, get_type_hints, overload) _HAS_PEP604_SUPPORT = sys.version_info[:3] >= (3, 10, 0) # PEP 604 if _HAS_PEP604_SUPPORT: _HAS_PEP560_SUPPORT = True else: _HAS_PEP560_SUPPORT = sys.version_info[:3] >= (3, 7, 0) # PEP 560 _RETURN = 'return' if _HAS_PEP604_SUPPORT: from types import UnionType from typing import ForwardRef, _GenericAlias elif _HAS_PEP560_SUPPORT: from typing import ForwardRef, _GenericAlias else: from typing import _Union logger = logging.getLogger('inject') _INJECTOR = None # Shared injector instance. _INJECTOR_LOCK = threading.RLock() # Guards injector initialization. _BINDING_LOCK = threading.RLock() # Guards runtime bindings. Injectable = Union[object, Any] T = TypeVar('T', bound=Injectable) Binding = Union[Type[Injectable], Hashable] Constructor = Callable[[], Injectable] Provider = Constructor BinderCallable = Callable[['Binder'], Optional['Binder']] class ConstructorTypeError(TypeError): def __init__(self, constructor: Callable, previous_error: TypeError): super(ConstructorTypeError, self).__init__("%s raised an error: %s" % (constructor, previous_error)) class Binder(object): _bindings: Dict[Binding, Constructor] def __init__(self, allow_override: bool = False) -> None: self._bindings = {} self.allow_override = allow_override def install(self, config: BinderCallable) -> 'Binder': """Install another callable configuration.""" config(self) return self def bind(self, cls: Binding, instance: T) -> 'Binder': """Bind a class to an instance.""" self._check_class(cls) b = lambda: instance self._bindings[cls] = b self._maybe_bind_forward(cls, b) logger.debug('Bound %s to an instance %s', cls, instance) return self def bind_to_constructor(self, cls: Binding, constructor: Constructor) -> 'Binder': """Bind a class to a callable singleton constructor.""" self._check_class(cls) if constructor is None: raise InjectorException('Constructor cannot be None, key=%s' % cls) b = _ConstructorBinding(constructor) self._bindings[cls] = b self._maybe_bind_forward(cls, b) logger.debug('Bound %s to a constructor %s', cls, constructor) return self def bind_to_provider(self, cls: Binding, provider: Provider) -> 'Binder': """ Bind a class to a callable instance provider executed for each injection. A provider can be a normal function or a context manager. Both sync and async are supported. """ self._check_class(cls) if provider is None: raise InjectorException('Provider cannot be None, key=%s' % cls) b = provider self._bindings[cls] = b self._maybe_bind_forward(cls, b) logger.debug('Bound %s to a provider %s', cls, provider) return self def _check_class(self, cls: Binding) -> None: if cls is None: raise InjectorException('Binding key cannot be None') if not self.allow_override and cls in self._bindings: raise InjectorException('Duplicate binding, key=%s' % cls) if self._is_forward_str(cls): ref = ForwardRef(cls) if ref in self._bindings: raise InjectorException('Duplicate forward binding, i.e. "int" and int, key=%s', cls) def _maybe_bind_forward(self, cls: Binding, binding: Any) -> None: """Bind a string forward reference.""" if not _HAS_PEP560_SUPPORT: return if not isinstance(cls, str): return ref = ForwardRef(cls) self._bindings[ref] = binding logger.debug('Bound forward ref "%s"', cls) def _is_forward_str(self, cls: Binding) -> bool: return _HAS_PEP560_SUPPORT and isinstance(cls, str) class Injector(object): _bindings: Dict[Binding, Constructor] def __init__( self, config: Optional[BinderCallable] = None, bind_in_runtime: bool = True, allow_override: bool = False ): self._bind_in_runtime = bind_in_runtime if config: binder = Binder(allow_override) config(binder) self._bindings = binder._bindings else: self._bindings = {} @overload def get_instance(self, cls: Type[T]) -> T: ... @overload def get_instance(self, cls: Hashable) -> Injectable: ... def get_instance(self, cls: Binding) -> Injectable: """Return an instance for a class.""" binding = self._bindings.get(cls) if binding: return binding() # Try to create a runtime binding. with _BINDING_LOCK: binding = self._bindings.get(cls) if binding: return binding() if not self._bind_in_runtime: raise InjectorException( 'No binding was found for key=%s' % cls) if not callable(cls): raise InjectorException( 'Cannot create a runtime binding, the key is not callable, key=%s' % cls) try: instance = cls() except TypeError as previous_error: raise ConstructorTypeError(cls, previous_error) self._bindings[cls] = lambda: instance logger.debug( 'Created a runtime binding for key=%s, instance=%s', cls, instance) return instance class InjectorException(Exception): pass class _ConstructorBinding(Generic[T]): _instance: Optional[T] def __init__(self, constructor: Callable[[], T]) -> None: self._constructor = constructor self._created = False self._instance = None def __call__(self) -> T: if self._created and self._instance is not None: return self._instance with _BINDING_LOCK: if self._created and self._instance is not None: return self._instance self._instance = self._constructor() self._created = True return self._instance class _AttributeInjection(object): def __init__(self, cls: Binding) -> None: self._cls = cls def __get__(self, obj: Any, owner: Any) -> Injectable: inst = instance(self._cls) if isinstance(inst, contextlib._AsyncGeneratorContextManager): raise InjectorException( 'Fail to load _AsyncGeneratorContextManager, use autoparams, param or params instead of attr function') elif isinstance(inst, contextlib._GeneratorContextManager): with contextlib.ExitStack() as sync_stack: inst = sync_stack.enter_context(inst) return inst class _AttributeInjectionDataclass(Generic[T]): def __init__(self, cls: Binding) -> None: self._cls = cls def __get__(self, instance, owner) -> T: injector = get_injector() if injector is not None: return injector.get_instance(self._cls) raise AttributeError class _ParameterInjection(Generic[T]): __slots__ = ('_name', '_cls') def __init__(self, name: str, cls: Optional[Binding] = None) -> None: self._name = name self._cls = cls def __call__(self, func: Callable[..., Union[T, Awaitable[T]]]) -> Callable[..., Union[T, Awaitable[T]]]: if inspect.iscoroutinefunction(func): @wraps(func) async def async_injection_wrapper(*args: Any, **kwargs: Any) -> T: if self._name not in kwargs: kwargs[self._name] = instance(self._cls or self._name) async_func = cast(Callable[..., Awaitable[T]], func) return await async_func(*args, **kwargs) return async_injection_wrapper @wraps(func) def injection_wrapper(*args: Any, **kwargs: Any) -> T: if self._name not in kwargs: kwargs[self._name] = instance(self._cls or self._name) sync_func = cast(Callable[..., T], func) return sync_func(*args, **kwargs) return injection_wrapper class _ParametersInjection(Generic[T]): __slots__ = ('_params', ) def __init__(self, **kwargs: Any) -> None: self._params = kwargs @staticmethod def _aggregate_sync_stack( sync_stack: contextlib.ExitStack, provided_params: frozenset[str], kwargs: dict[str, Any] ) -> None: """Extracts context managers, aggregate them in an ExitStack and swap out the param value with results of running __enter__(). The result is equivalent to using `with` multiple times """ executed_kwargs = { param: sync_stack.enter_context(inst) for param, inst in kwargs.items() if param not in provided_params and isinstance(inst, contextlib._GeneratorContextManager) } kwargs.update(executed_kwargs) @staticmethod async def _aggregate_async_stack( async_stack: contextlib.AsyncExitStack, provided_params: frozenset[str], kwargs: dict[str, Any] ) -> None: """Similar to _aggregate_sync_stack, but for async context managers""" executed_kwargs = { param: await async_stack.enter_async_context(inst) for param, inst in kwargs.items() if param not in provided_params and isinstance(inst, contextlib._AsyncGeneratorContextManager) } kwargs.update(executed_kwargs) def __call__(self, func: Callable[..., Union[Awaitable[T], T]]) -> Callable[..., Union[Awaitable[T], T]]: if sys.version_info.major == 2: arg_names = inspect.getargspec(func).args else: arg_names = inspect.getfullargspec(func).args params_to_provide = self._params if inspect.iscoroutinefunction(func): @wraps(func) async def async_injection_wrapper(*args: Any, **kwargs: Any) -> T: provided_params = frozenset( arg_names[:len(args)]) | frozenset(kwargs.keys()) for param, cls in params_to_provide.items(): if param not in provided_params: kwargs[param] = instance(cls) async_func = cast(Callable[..., Awaitable[T]], func) try: with contextlib.ExitStack() as sync_stack: async with contextlib.AsyncExitStack() as async_stack: self._aggregate_sync_stack(sync_stack, provided_params, kwargs) await self._aggregate_async_stack(async_stack, provided_params, kwargs) return await async_func(*args, **kwargs) except TypeError as previous_error: raise ConstructorTypeError(func, previous_error) return async_injection_wrapper @wraps(func) def injection_wrapper(*args: Any, **kwargs: Any) -> T: provided_params = frozenset( arg_names[:len(args)]) | frozenset(kwargs.keys()) for param, cls in params_to_provide.items(): if param not in provided_params: kwargs[param] = instance(cls) sync_func = cast(Callable[..., T], func) try: with contextlib.ExitStack() as sync_stack: self._aggregate_sync_stack(sync_stack, provided_params, kwargs) return sync_func(*args, **kwargs) except TypeError as previous_error: raise ConstructorTypeError(func, previous_error) return injection_wrapper def configure( config: Optional[BinderCallable] = None, bind_in_runtime: bool = True, allow_override: bool = False, clear: bool = False, once: bool = False ) -> Injector: """Create an injector with a callable config or raise an exception when already configured.""" global _INJECTOR if clear and once: raise InjectorException('clear and once are mutually exclusive, only one can be True') with _INJECTOR_LOCK: if _INJECTOR: if clear: _clear_injector() elif once: return _INJECTOR else: raise InjectorException('Injector is already configured') _INJECTOR = Injector(config, bind_in_runtime=bind_in_runtime, allow_override=allow_override) logger.debug('Created and configured an injector, config=%s', config) return _INJECTOR def configure_once( config: Optional[BinderCallable] = None, bind_in_runtime: bool = True, allow_override: bool = False ) -> Injector: """Create an injector with a callable config if not present, otherwise, do nothing. Deprecated, use `configure(once=True)` instead. """ with _INJECTOR_LOCK: if _INJECTOR: return _INJECTOR return configure(config, bind_in_runtime=bind_in_runtime, allow_override=allow_override) def clear_and_configure( config: Optional[BinderCallable] = None, bind_in_runtime: bool = True, allow_override: bool = False ) -> Injector: """Clear an existing injector and create another one with a callable config. Deprecated, use configure(clear=True) instead. """ with _INJECTOR_LOCK: _clear_injector() return configure(config, bind_in_runtime=bind_in_runtime, allow_override=allow_override) def is_configured() -> bool: """Return true if an injector is already configured.""" with _INJECTOR_LOCK: return _INJECTOR is not None def clear() -> None: """Clear an existing injector if present.""" _clear_injector() def _clear_injector() -> None: """Clear an existing injector if present.""" global _INJECTOR with _INJECTOR_LOCK: if _INJECTOR is None: return _INJECTOR = None logger.debug('Cleared an injector') @overload def instance(cls: Type[T]) -> T: ... @overload def instance(cls: Hashable) -> Injectable: ... def instance(cls: Binding) -> Injectable: """Inject an instance of a class.""" return get_injector_or_die().get_instance(cls) @overload def attr(cls: Type[T]) -> T: ... @overload def attr(cls: Hashable) -> Injectable: ... def attr(cls: Binding) -> Injectable: """Return a attribute injection (descriptor).""" return _AttributeInjection(cls) @overload def attr_dc(cls: Type[T]) -> T: ... @overload def attr_dc(cls: Hashable) -> Injectable: ... def attr_dc(cls: Binding) -> Injectable: """Return a attribute injection (descriptor).""" return _AttributeInjectionDataclass(cls) def param(name: str, cls: Optional[Binding] = None) -> Callable: """Deprecated, use @inject.params. Return a decorator which injects an arg into a function.""" return _ParameterInjection(name, cls) def params(**args_to_classes: Binding) -> Callable: """Return a decorator which injects args into a function. For example:: @inject.params(cache=RedisCache, db=DbInterface) def sign_up(name, email, cache, db): pass """ return _ParametersInjection(**args_to_classes) def autoparams(*selected: str) -> Callable: """Return a decorator that will inject args into a function using type annotations, Python >= 3.5 only. For example:: @inject.autoparams def refresh_cache(cache: RedisCache, db: DbInterface): pass There is an option to specify which arguments we want to inject without attempts of injecting everything: For example:: @inject.autoparams('cache', 'db') def sign_up(name, email, cache: RedisCache, db: DbInterface): pass """ only_these: Set[str] = set() def autoparams_decorator(fn: Callable[..., T]) -> Callable[..., T]: if inspect.isclass(fn): types = get_type_hints(fn.__init__) else: types = get_type_hints(fn) # Skip the return annotation. types = {name: typ for name, typ in types.items() if name != _RETURN} # Convert Union types into single types, i.e. Union[A, None] => A. types = {name: _unwrap_union_arg(typ) for name, typ in types.items()} # Filter types if selected args present. if only_these: types = {name: typ for name, typ in types.items() if name in only_these} wrapper: _ParametersInjection[T] = _ParametersInjection(**types) return wrapper(fn) target = selected[0] if selected else None if len(selected) == 1 and callable(target): return autoparams_decorator(target) only_these.update(selected) return autoparams_decorator def get_injector() -> Optional[Injector]: """Return the current injector or None.""" return _INJECTOR def get_injector_or_die() -> Injector: """Return the current injector or raise an InjectorException.""" injector = _INJECTOR if not injector: raise InjectorException('No injector is configured') return injector def _unwrap_union_arg(typ): """Return the first type A in typing.Union[A, B] or typ if not Union.""" if not _is_union_type(typ): return typ return typ.__args__[0] def _is_union_type(typ): """Test if the type is a union type. Examples:: is_union_type(int) == False is_union_type(Union) == True is_union_type(Union[int, int]) == False is_union_type(Union[T, int]) == True Source: https://github.com/ilevkivskyi/typing_inspect/blob/master/typing_inspect.py """ if _HAS_PEP604_SUPPORT: return (typ is Union or isinstance(typ, UnionType) or isinstance(typ, _GenericAlias) and typ.__origin__ is Union) elif _HAS_PEP560_SUPPORT: return (typ is Union or isinstance(typ, _GenericAlias) and typ.__origin__ is Union) return type(typ) is _Union python-inject-5.3.0/src/inject/py.typed000066400000000000000000000000001502523167400200470ustar00rootroot00000000000000python-inject-5.3.0/test/000077500000000000000000000000001502523167400152765ustar00rootroot00000000000000python-inject-5.3.0/test/__init__.py000066400000000000000000000004161502523167400174100ustar00rootroot00000000000000from unittest import TestCase import asyncio import inject class BaseTestInject(TestCase): def tearDown(self): inject.clear() def run_async(self, awaitable): loop = asyncio.get_event_loop() return loop.run_until_complete(awaitable)python-inject-5.3.0/test/test_attr.py000066400000000000000000000017521502523167400176660ustar00rootroot00000000000000import inject from test import BaseTestInject class TestInjectAttr(BaseTestInject): def test_attr(self): class MyClass(object): field = inject.attr(int) inject.configure(lambda binder: binder.bind(int, 123)) my = MyClass() value0 = my.field value1 = my.field assert value0 == 123 assert value1 == 123 def test_class_attr(self): class MyClass(object): field = inject.attr(int) inject.configure(lambda binder: binder.bind(int, 123)) value0 = MyClass.field value1 = MyClass.field assert value0 == 123 assert value1 == 123 class TestInjectAttrDataclass(BaseTestInject): def test_class_attr_dc(self): class MyClass(object): field = inject.attr_dc(int) inject.configure(lambda binder: binder.bind(int, 123)) value0 = MyClass.field value1 = MyClass.field assert value0 == 123 assert value1 == 123 python-inject-5.3.0/test/test_autoparams.py000066400000000000000000000167101502523167400210700ustar00rootroot00000000000000import sys from typing import Optional from test import BaseTestInject import inject class A: pass class B: pass class C: pass class TestInjectEmptyAutoparamsWithBraces(BaseTestInject): @staticmethod def _get_decorator(): return inject.autoparams() def test_autoparams_by_class(self): @self._get_decorator() def test_func(val: int = None): return val inject.configure(lambda binder: binder.bind(int, 123)) assert test_func() == 123 assert test_func(val=321) == 321 def test_autoparams_multi(self): @self._get_decorator() def test_func(a: A, b: B, *, c: C): return a, b, c def config(binder): binder.bind(A, 1) binder.bind(B, 2) binder.bind(C, 3) inject.configure(config) assert test_func() == (1, 2, 3) assert test_func(10) == (10, 2, 3) assert test_func(10, 20) == (10, 20, 3) assert test_func(10, 20, c=30) == (10, 20, 30) assert test_func(a='a') == ('a', 2, 3) assert test_func(b='b') == (1, 'b', 3) assert test_func(c='c') == (1, 2, 'c') assert test_func(a=10, c=30) == (10, 2, 30) assert test_func(c=30, b=20, a=10) == (10, 20, 30) assert test_func(10, b=20) == (10, 20, 3) def test_autoparams_strings(self): @self._get_decorator() def test_func(a: 'A', b: 'B', *, c: 'C'): return a, b, c def config(binder): binder.bind(A, 1) binder.bind(B, 2) binder.bind(C, 3) inject.configure(config) assert test_func() == (1, 2, 3) assert test_func(10) == (10, 2, 3) assert test_func(10, 20) == (10, 20, 3) assert test_func(10, 20, c=30) == (10, 20, 30) assert test_func(a='a') == ('a', 2, 3) assert test_func(b='b') == (1, 'b', 3) assert test_func(c='c') == (1, 2, 'c') assert test_func(a=10, c=30) == (10, 2, 30) assert test_func(c=30, b=20, a=10) == (10, 20, 30) assert test_func(10, b=20) == (10, 20, 3) def test_autoparams_with_defaults(self): @self._get_decorator() def test_func(a=1, b: 'B' = None, *, c: 'C' = 300): return a, b, c def config(binder): binder.bind(B, 2) binder.bind(C, 3) inject.configure(config) assert test_func() == (1, 2, 3) assert test_func(10) == (10, 2, 3) assert test_func(10, 20) == (10, 20, 3) assert test_func(10, 20, c=30) == (10, 20, 30) assert test_func(a='a') == ('a', 2, 3) assert test_func(b='b') == (1, 'b', 3) assert test_func(c='c') == (1, 2, 'c') assert test_func(a=10, c=30) == (10, 2, 30) assert test_func(c=30, b=20, a=10) == (10, 20, 30) assert test_func(10, b=20) == (10, 20, 3) def test_autoparams_on_method(self): class Test: @self._get_decorator() def func(self, a=1, b: 'B' = None, *, c: 'C' = None): return self, a, b, c def config(binder): binder.bind(B, 2) binder.bind(C, 3) inject.configure(config) test = Test() assert test.func() == (test, 1, 2, 3) assert test.func(10) == (test, 10, 2, 3) assert test.func(10, 20) == (test, 10, 20, 3) assert test.func(10, 20, c=30) == (test, 10, 20, 30) assert test.func(a='a') == (test, 'a', 2, 3) assert test.func(b='b') == (test, 1, 'b', 3) assert test.func(c='c') == (test, 1, 2, 'c') assert test.func(a=10, c=30) == (test, 10, 2, 30) assert test.func(c=30, b=20, a=10) == (test, 10, 20, 30) assert test.func(10, b=20) == (test, 10, 20, 3) def test_autoparams_on_classmethod(self): class Test: # note inject must be *before* classmethod! @classmethod @self._get_decorator() def func(cls, a=1, b: 'B' = None, *, c: 'C' = None): return cls, a, b, c def config(binder): binder.bind(B, 2) binder.bind(C, 3) inject.configure(config) assert Test.func() == (Test, 1, 2, 3) assert Test.func(10) == (Test, 10, 2, 3) assert Test.func(10, 20) == (Test, 10, 20, 3) assert Test.func(10, 20, c=30) == (Test, 10, 20, 30) assert Test.func(a='a') == (Test, 'a', 2, 3) assert Test.func(b='b') == (Test, 1, 'b', 3) assert Test.func(c='c') == (Test, 1, 2, 'c') assert Test.func(a=10, c=30) == (Test, 10, 2, 30) assert Test.func(c=30, b=20, a=10) == (Test, 10, 20, 30) assert Test.func(10, b=20) == (Test, 10, 20, 3) def test_autoparams_on_classmethod_ob_object(self): class Test: # note inject must be *before* classmethod! @classmethod @self._get_decorator() def func(cls, a=1, b: 'B' = None, *, c: 'C' = None): return cls, a, b, c def config(binder): binder.bind(B, 2) binder.bind(C, 3) inject.configure(config) test = Test assert test.func() == (Test, 1, 2, 3) assert test.func(10) == (Test, 10, 2, 3) assert test.func(10, 20) == (Test, 10, 20, 3) assert test.func(10, 20, c=30) == (Test, 10, 20, 30) assert test.func(a='a') == (Test, 'a', 2, 3) assert test.func(b='b') == (Test, 1, 'b', 3) assert test.func(c='c') == (Test, 1, 2, 'c') assert test.func(a=10, c=30) == (Test, 10, 2, 30) assert test.func(c=30, b=20, a=10) == (Test, 10, 20, 30) assert test.func(10, b=20) == (Test, 10, 20, 3) def test_autoparams_omits_return_type(self): @self._get_decorator() def test_func(a: str) -> int: return a def config(binder): binder.bind(str, 'bazinga') inject.configure(config) assert test_func() == 'bazinga' class TestInjectEmptyAutoparamsNoBraces(TestInjectEmptyAutoparamsWithBraces): @staticmethod def _get_decorator(): return inject.autoparams class TestInjectSelectedAutoparams(BaseTestInject): def test_autoparams_only_selected(self): @inject.autoparams('a', 'c') def test_func(a: 'A', b: 'B', *, c: 'C'): return a, b, c def config(binder): binder.bind(A, 1) binder.bind(B, 2) binder.bind(C, 3) inject.configure(config) self.assertRaises(TypeError, test_func) self.assertRaises(TypeError, test_func, a=1, c=3) def test_autoparams_only_selected_with_optional(self): @inject.autoparams('a', 'c') def test_func(a: 'A', b: 'B', *, c: Optional[C] = None): return a, b, c def config(binder): binder.bind(A, 1) binder.bind(B, 2) binder.bind(C, 3) inject.configure(config) self.assertRaises(TypeError, test_func) self.assertRaises(TypeError, test_func, a=1, c=3) def test_autoparams_only_selected_with_optional_pep604_union(self): if not sys.version_info[:3] >= (3, 10, 0): return @inject.autoparams('a', 'c') def test_func(a: 'A', b: 'B', *, c: C | None = None): return a, b, c def config(binder): binder.bind(A, 1) binder.bind(B, 2) binder.bind(C, 3) inject.configure(config) self.assertRaises(TypeError, test_func) self.assertRaises(TypeError, test_func, a=1, c=3) python-inject-5.3.0/test/test_binder.py000066400000000000000000000030631502523167400201540ustar00rootroot00000000000000from unittest import TestCase from inject import Binder, InjectorException class TestBinder(TestCase): def test_bind(self): binder = Binder() binder.bind(int, 123) assert int in binder._bindings def test_bind__class_required(self): binder = Binder() self.assertRaisesRegex(InjectorException, 'Binding key cannot be None', binder.bind, None, None) def test_bind__duplicate_binding(self): binder = Binder() binder.bind(int, 123) self.assertRaisesRegex(InjectorException, "Duplicate binding", binder.bind, int, 456) def test_bind__allow_override(self): binder = Binder(allow_override=True) binder.bind(int, 123) binder.bind(int, 456) assert int in binder._bindings def test_bind_provider(self): provider = lambda: 123 binder = Binder() binder.bind_to_provider(int, provider) assert binder._bindings[int] is provider def test_bind_provider__provider_required(self): binder = Binder() self.assertRaisesRegex(InjectorException, "Provider cannot be None", binder.bind_to_provider, int, None) def test_bind_constructor(self): constructor = lambda: 123 binder = Binder() binder.bind_to_constructor(int, constructor) assert binder._bindings[int]._constructor is constructor def test_bind_constructor__constructor_required(self): binder = Binder() self.assertRaisesRegex(InjectorException, "Constructor cannot be None", binder.bind_to_constructor, int, None) python-inject-5.3.0/test/test_context_manager.py000066400000000000000000000046671502523167400221020ustar00rootroot00000000000000import contextlib import inject from test import BaseTestInject class Destroyable: def __init__(self): self.started = True def destroy(self): self.started = False class MockFile(Destroyable): ... class MockConnection(Destroyable): ... class MockFoo(Destroyable): ... @contextlib.contextmanager def get_file_sync(): obj = MockFile() yield obj obj.destroy() @contextlib.contextmanager def get_conn_sync(): obj = MockConnection() yield obj obj.destroy() @contextlib.contextmanager def get_foo_sync(): obj = MockFoo() yield obj obj.destroy() @contextlib.asynccontextmanager async def get_file_async(): obj = MockFile() yield obj obj.destroy() @contextlib.asynccontextmanager async def get_conn_async(): obj = MockConnection() yield obj obj.destroy() class TestContextManagerFunctional(BaseTestInject): def test_provider_as_context_manager_sync(self): def config(binder): binder.bind_to_provider(MockFile, get_file_sync) binder.bind(int, 100) binder.bind_to_provider(str, lambda: "Hello") binder.bind_to_provider(MockConnection, get_conn_sync) inject.configure(config) @inject.autoparams() def mock_func(conn: MockConnection, name: str, f: MockFile, number: int): assert f.started assert conn.started assert name == "Hello" assert number == 100 return f, conn f_, conn_ = mock_func() assert not f_.started assert not conn_.started def test_provider_as_context_manager_async(self): def config(binder): binder.bind_to_provider(MockFile, get_file_async) binder.bind(int, 100) binder.bind_to_provider(str, lambda: "Hello") binder.bind_to_provider(MockConnection, get_conn_async) binder.bind_to_provider(MockFoo, get_foo_sync) inject.configure(config) @inject.autoparams() async def mock_func(conn: MockConnection, name: str, f: MockFile, number: int, foo: MockFoo): assert f.started assert conn.started assert foo.started assert name == "Hello" assert number == 100 return f, conn, foo f_, conn_, foo_ = self.run_async(mock_func()) assert not f_.started assert not conn_.started assert not foo_.startedpython-inject-5.3.0/test/test_dataclass.py000066400000000000000000000020061502523167400206440ustar00rootroot00000000000000from dataclasses import dataclass import inject from test import BaseTestInject from typing import ClassVar class TestInjectAttr(BaseTestInject): def test_attr_on_dataclass_class_var_raises_error(self): with self.assertRaises(inject.InjectorException): @dataclass class MyClass: field: ClassVar[int] = inject.attr(int) class TestInjectAttrDataclass(BaseTestInject): def test_attr_dc(self): @dataclass class MyClass(object): field = inject.attr_dc(int) inject.configure(lambda binder: binder.bind(int, 123)) my = MyClass() value0 = my.field value1 = my.field assert value0 == 123 assert value1 == 123 def test_attr_on_dataclass_class_var_works(self): @dataclass class MyClass: field: ClassVar[int] = inject.attr_dc(int) inject.configure(lambda binder: binder.bind(int, 123)) assert MyClass().field == 123 assert MyClass.field == 123 python-inject-5.3.0/test/test_functional.py000066400000000000000000000070061502523167400210540ustar00rootroot00000000000000from unittest import TestCase import inject from inject import autoparams, ConstructorTypeError class TestFunctional(TestCase): def tearDown(self): inject.clear() def test(self): class Config(object): def __init__(self, greeting): self.greeting = greeting class Cache(object): config = inject.attr(Config) def load_greeting(self): return self.config.greeting class User(object): cache = inject.attr(Cache) def __init__(self, name): self.name = name def greet(self): return '%s, %s' % (self.cache.load_greeting(), self.name) def config(binder): binder.bind(Config, Config('Hello')) inject.configure(config) user = User('John Doe') greeting = user.greet() assert greeting == 'Hello, John Doe' def test_class_with_restricted_bool_casting(self): class DataFrame(object): def __nonzero__(self): """Python 2""" raise NotImplementedError('Casting to boolean is not allowed') def __bool__(self): """Python 3""" raise NotImplementedError('Casting to boolean is not allowed') def create_data_frame(): return DataFrame() def config(binder): binder.bind_to_constructor(DataFrame, create_data_frame) inject.configure(config) assert type(inject.instance(DataFrame)) is DataFrame # There should not be an error when we fetch created instance assert type(inject.instance(DataFrame)) is DataFrame def test_class_support_in_autoparams_programmaticaly(self): class AnotherClass: pass class SomeClass: def __init__(self, another_object: AnotherClass): self.another_object = another_object def config(binder): binder.bind_to_constructor(SomeClass, autoparams()(SomeClass)) binder.bind_to_constructor(AnotherClass, autoparams()(AnotherClass)) inject.configure(config) some_object = inject.instance(SomeClass) assert type(some_object) is SomeClass assert type(some_object.another_object) is AnotherClass def test_error_message(self): class SomeClass: def __init__(self, missing_arg): self._missing_arg = missing_arg class AnotherClass(SomeClass): pass def create_some_class(missing_arg): return AnotherClass(missing_arg) def config(binder): binder.bind_to_constructor(SomeClass, autoparams()(SomeClass)) binder.bind_to_constructor(AnotherClass, create_some_class) inject.configure() # covers case when no constructor provided try: inject.instance(SomeClass) except ConstructorTypeError as err: assert 'SomeClass' in str(err) assert 'missing_arg' in str(err) inject.clear_and_configure(config) # covers case with provided constructor try: inject.instance(SomeClass) except ConstructorTypeError as err: assert 'SomeClass' in str(err) assert 'missing_arg' in str(err) try: inject.instance(AnotherClass) except TypeError as err: assert not isinstance(err, ConstructorTypeError) assert 'create_some_class' in str(err) assert 'missing_arg' in str(err)python-inject-5.3.0/test/test_inject_configuration.py000066400000000000000000000043751502523167400231230ustar00rootroot00000000000000import inject from inject import InjectorException from test import BaseTestInject class TestInjectConfiguration(BaseTestInject): def test_configure__should_create_injector(self): injector0 = inject.configure() injector1 = inject.get_injector() assert injector0 assert injector0 is injector1 def test_configure__should_add_bindings(self): injector = inject.configure(lambda binder: binder.bind(int, 123)) instance = injector.get_instance(int) assert instance == 123 def test_configure__already_configured(self): inject.configure() self.assertRaisesRegex(InjectorException, 'Injector is already configured', inject.configure) def test_configure_once__should_create_injector(self): injector = inject.configure_once() assert inject.get_injector() is injector def test_configure_once__should_return_existing_injector_when_present(self): injector0 = inject.configure() injector1 = inject.configure_once() assert injector0 is injector1 def test_is_configured__should_return_true_when_injector_present(self): assert inject.is_configured() is False inject.configure() assert inject.is_configured() is True inject.clear() assert inject.is_configured() is False def test_clear_and_configure(self): injector0 = inject.configure() injector1 = inject.clear_and_configure() # No exception. assert injector0 assert injector1 assert injector1 is not injector0 def test_get_injector_or_die(self): self.assertRaisesRegex(InjectorException, 'No injector is configured', inject.get_injector_or_die) def test_configure__runtime_binding_disabled(self): injector = inject.configure(bind_in_runtime=False) self.assertRaisesRegex(InjectorException, "No binding was found for key=<.* 'int'>", injector.get_instance, int) def test_configure__install_allow_override(self): def base_config(binder): binder.bind(int, 123) def config(binder): binder.install(base_config) binder.bind(int, 456) injector = inject.configure(config, allow_override=True) assert injector.get_instance(int) == 456 python-inject-5.3.0/test/test_injector.py000066400000000000000000000034501502523167400205260ustar00rootroot00000000000000from random import random from unittest import TestCase from inject import Injector, InjectorException class TestInjector(TestCase): def test_instance_binding__should_use_the_same_instance(self): injector = Injector(lambda binder: binder.bind(int, 123)) instance = injector.get_instance(int) assert instance == 123 def test_constructor_binding__should_construct_singleton(self): injector = Injector(lambda binder: binder.bind_to_constructor(int, random)) instance0 = injector.get_instance(int) instance1 = injector.get_instance(int) assert instance0 == instance1 def test_provider_binding__should_call_provider_for_each_injection(self): injector = Injector(lambda binder: binder.bind_to_provider(int, random)) instance0 = injector.get_instance(int) instance1 = injector.get_instance(int) assert instance0 != instance1 def test_runtime_binding__should_create_runtime_singleton(self): class MyClass(object): pass injector = Injector() instance0 = injector.get_instance(MyClass) instance1 = injector.get_instance(MyClass) assert instance0 is instance1 assert isinstance(instance0, MyClass) def test_runtime_binding__not_callable(self): injector = Injector() self.assertRaisesRegex(InjectorException, 'Cannot create a runtime binding, the key is not callable, key=123', injector.get_instance, 123) def test_runtime_binding__disabled(self): injector = Injector(bind_in_runtime=False) self.assertRaisesRegex(InjectorException, "No binding was found for key=<.* 'int'>", injector.get_instance, int) python-inject-5.3.0/test/test_instance.py000066400000000000000000000003751502523167400205200ustar00rootroot00000000000000import inject from test import BaseTestInject class TestInjectInstance(BaseTestInject): def test_instance(self): inject.configure(lambda binder: binder.bind(int, 123)) instance = inject.instance(int) assert instance == 123 python-inject-5.3.0/test/test_param.py000066400000000000000000000016041502523167400200100ustar00rootroot00000000000000import inject from test import BaseTestInject import inspect import asyncio class TestInjectParams(BaseTestInject): def test_param_by_name(self): @inject.param('val') def test_func(val=None): return val inject.configure(lambda binder: binder.bind('val', 123)) assert test_func() == 123 assert test_func(val=321) == 321 def test_param_by_class(self): @inject.param('val', int) def test_func(val): return val inject.configure(lambda binder: binder.bind(int, 123)) assert test_func() == 123 def test_async_param(self): @inject.param('val') async def test_func(val): return val inject.configure(lambda binder: binder.bind('val', 123)) assert inspect.iscoroutinefunction(test_func) assert self.run_async(test_func()) == 123 python-inject-5.3.0/test/test_params.py000066400000000000000000000121201502523167400201660ustar00rootroot00000000000000import inject from test import BaseTestInject import inspect import asyncio class TestInjectParams(BaseTestInject): def test_params(self): @inject.params(val=int) def test_func(val): return val inject.configure(lambda binder: binder.bind(int, 123)) assert test_func() == 123 assert test_func(321) == 321 assert test_func(val=42) == 42 def test_params_multi(self): @inject.params(a='A', b='B', c='C') def test_func(a, b, c): return a, b, c def config(binder): binder.bind('A', 1) binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) assert test_func() == (1, 2, 3) assert test_func(10) == (10, 2, 3) assert test_func(10, 20) == (10, 20, 3) assert test_func(10, 20, 30) == (10, 20, 30) assert test_func(a='a') == ('a', 2, 3) assert test_func(b='b') == (1, 'b', 3) assert test_func(c='c') == (1, 2, 'c') assert test_func(a=10, c=30) == (10, 2, 30) assert test_func(c=30, b=20, a=10) == (10, 20, 30) assert test_func(10, b=20) == (10, 20, 3) def test_params_with_defaults(self): # note the inject overrides default parameters @inject.params(b='B', c='C') def test_func(a=1, b=None, c=300): return a, b, c def config(binder): binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) assert test_func() == (1, 2, 3) assert test_func(10) == (10, 2, 3) assert test_func(10, 20) == (10, 20, 3) assert test_func(10, 20, 30) == (10, 20, 30) assert test_func(a='a') == ('a', 2, 3) assert test_func(b='b') == (1, 'b', 3) assert test_func(c='c') == (1, 2, 'c') assert test_func(a=10, c=30) == (10, 2, 30) assert test_func(c=30, b=20, a=10) == (10, 20, 30) assert test_func(10, b=20) == (10, 20, 3) def test_params_on_method(self): class Test: @inject.params(b='B', c='C') def func(self, a=1, b=None, c=None): return self, a, b, c def config(binder): binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) test = Test() assert test.func() == (test, 1, 2, 3) assert test.func(10) == (test, 10, 2, 3) assert test.func(10, 20) == (test, 10, 20, 3) assert test.func(10, 20, 30) == (test, 10, 20, 30) assert test.func(a='a') == (test, 'a', 2, 3) assert test.func(b='b') == (test, 1, 'b', 3) assert test.func(c='c') == (test, 1, 2, 'c') assert test.func(a=10, c=30) == (test, 10, 2, 30) assert test.func(c=30, b=20, a=10) == (test, 10, 20, 30) assert test.func(10, b=20) == (test, 10, 20, 3) def test_params_on_classmethod(self): class Test: # note inject must be *before* classmethod! @classmethod @inject.params(b='B', c='C') def func(cls, a=1, b=None, c=None): return cls, a, b, c def config(binder): binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) assert Test.func() == (Test, 1, 2, 3) assert Test.func(10) == (Test, 10, 2, 3) assert Test.func(10, 20) == (Test, 10, 20, 3) assert Test.func(10, 20, 30) == (Test, 10, 20, 30) assert Test.func(a='a') == (Test, 'a', 2, 3) assert Test.func(b='b') == (Test, 1, 'b', 3) assert Test.func(c='c') == (Test, 1, 2, 'c') assert Test.func(a=10, c=30) == (Test, 10, 2, 30) assert Test.func(c=30, b=20, a=10) == (Test, 10, 20, 30) assert Test.func(10, b=20) == (Test, 10, 20, 3) def test_params_on_classmethod_ob_object(self): class Test: # note inject must be *before* classmethod! @classmethod @inject.params(b='B', c='C') def func(cls, a=1, b=None, c=None): return cls, a, b, c def config(binder): binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) test = Test assert test.func() == (Test, 1, 2, 3) assert test.func(10) == (Test, 10, 2, 3) assert test.func(10, 20) == (Test, 10, 20, 3) assert test.func(10, 20, 30) == (Test, 10, 20, 30) assert test.func(a='a') == (Test, 'a', 2, 3) assert test.func(b='b') == (Test, 1, 'b', 3) assert test.func(c='c') == (Test, 1, 2, 'c') assert test.func(a=10, c=30) == (Test, 10, 2, 30) assert test.func(c=30, b=20, a=10) == (Test, 10, 20, 30) assert test.func(10, b=20) == (Test, 10, 20, 3) def test_async_params(self): @inject.params(val=int) async def test_func(val): return val inject.configure(lambda binder: binder.bind(int, 123)) assert inspect.iscoroutinefunction(test_func) assert self.run_async(test_func()) == 123 assert self.run_async(test_func(321)) == 321 assert self.run_async(test_func(val=42)) == 42