sinj


Namesinj JSON
Version 0.3.1 PyPI version JSON
download
home_page
SummaryIoC container
upload_time2023-09-08 14:36:05
maintainer
docs_urlNone
author
requires_python>=3.7
licenseMIT License Copyright (c) 2023 Marius Kavaliauskas Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords ioc inverse-of-control injection dependency-injection dependencies-container
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
# 💉 sinj

`sinj` (**S**imple **Inj**ect) is yet another IoC framework for python. If you try to avoid global variables and singletons you might end up with a complex graph of dependencies in your application. With `sinj` everything is just flat. If you are coming from Java or C# you might be more familiar with IoC frameworks where dependencies are resolved by interface. In python we do not have interfaces and strict types so here we resolve dependencies by constructor argument names or "inject labels".

# Basic usage and examples

```python
import sinj
c = sinj.Container() # create dependencies container
c.register(SomeClass, "some_class") # add labeled class into container
c.resolve("some_class") # resolve instance by given label
c.inject(some_instance, "some_instance") # add resolved instance to an index
```


The simplest example:

```python
import sinj

class A:
    def a(self):
        return "a"

class B:
    def __init__(self, a):
        self._a = a
    
    def b(self):
        return self._a() + " b"

ioc_container = sinj.Container()
ioc_container.register(A, "a")
ioc_container.register(B, "b")

b = ioc_container.resolve("b")
print(b.b()) # -> "a b"
```

The same example with annotated classes:

```python
import sinj

class A:
    inject = "a" # this label will be used to resolve instance of A
    def a(self):
        return "a"

class B:
    inject = "b" # this label will be used to resolve instance of B
    def __init__(self, a): # instance of A is injected here
        self._a = a
    
    def b(self):
        return self._a() + " b"

ioc_container = sinj.Container()
ioc_container.register(A) # no need to specify label here
ioc_container.register(B) # but you can overwrite it if you want

b = ioc_container.resolve("b")
print(b.b()) # -> "a b"
```

More examples will be available in `./examples`


# Errors


- `sinj.DependencyNotFoundError` - thrown on `resolve` when dependency is not found for a given label (and it is not optional).
- `sinj.CircularDependencyError` - thrown on `resolve` when circular dependency is detected.
- `sinj.DependencyConflictError` - thrown on `register` or `inject` when the container already has something by the label.
- `sinj.DependencyNotMappedError` - thrown on `register` or `inject` when the class is not annotated and the label is not provided in register method.


# Validating types

You have an option to pass a validator into `sinj.Container` to check injected types. `sinj` has a simple built in validator which is able to log warnings or raise errors. You can create more complicated validators if you want, it is just a class with `validate(self, instance, param: inspect.Parameter):` method:

```python

class TypeValidator:
    def __init__(self, log_warning=True, raise_error=False):
        self._log_warning = log_warning
        self._raise_error = raise_error

    def validate(self, instance, param: inspect.Parameter):
        err_msg = self._get_err_msg(instance, param)
        if err_msg is None:
            return

        if self._log_warning:
            logger.warning(err_msg)

        if self._raise_error:
            raise TypeValidatorError(err_msg)

    def _get_err_msg(self, instance, param: inspect.Parameter):
        if not hasattr(instance, "__class__"):
            return f"could not determine class of instance for {param.name}"

        if param.annotation == param.empty:
            return None

        if not inspect.isclass(param.annotation):
            return f"param annotated with a non-class for {param.name}"

        if not issubclass(instance.__class__, param.annotation):
            return f"instance is not derived from annotated type for {param.name}"

        return None

ioc_container = sinj.Container(validator=TypeValidator(True, True))
```


# Install


### From [pypi.org](https://pypi.org/project/sinj/)

```bash
pip install sinj
```

### From [repository](https://gitlab.com/mrsk/sinj)

```bash
pip install git+https://gitlab.com/mrsk/sinj
```


            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "sinj",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "ioc,inverse-of-control,injection,dependency-injection,dependencies-container",
    "author": "",
    "author_email": "Marius Kavaliauskas <mariuskava+sinj@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/1d/30/29ff4f662b0baae7b16fe556c151ba77222b270c5a2ed842e4ae2c9de83d/sinj-0.3.1.tar.gz",
    "platform": null,
    "description": "\n# \ud83d\udc89 sinj\n\n`sinj` (**S**imple **Inj**ect) is yet another IoC framework for python. If you try to avoid global variables and singletons you might end up with a complex graph of dependencies in your application. With `sinj` everything is just flat. If you are coming from Java or C# you might be more familiar with IoC frameworks where dependencies are resolved by interface. In python we do not have interfaces and strict types so here we resolve dependencies by constructor argument names or \"inject labels\".\n\n# Basic usage and examples\n\n```python\nimport sinj\nc = sinj.Container() # create dependencies container\nc.register(SomeClass, \"some_class\") # add labeled class into container\nc.resolve(\"some_class\") # resolve instance by given label\nc.inject(some_instance, \"some_instance\") # add resolved instance to an index\n```\n\n\nThe simplest example:\n\n```python\nimport sinj\n\nclass A:\n    def a(self):\n        return \"a\"\n\nclass B:\n    def __init__(self, a):\n        self._a = a\n    \n    def b(self):\n        return self._a() + \" b\"\n\nioc_container = sinj.Container()\nioc_container.register(A, \"a\")\nioc_container.register(B, \"b\")\n\nb = ioc_container.resolve(\"b\")\nprint(b.b()) # -> \"a b\"\n```\n\nThe same example with annotated classes:\n\n```python\nimport sinj\n\nclass A:\n    inject = \"a\" # this label will be used to resolve instance of A\n    def a(self):\n        return \"a\"\n\nclass B:\n    inject = \"b\" # this label will be used to resolve instance of B\n    def __init__(self, a): # instance of A is injected here\n        self._a = a\n    \n    def b(self):\n        return self._a() + \" b\"\n\nioc_container = sinj.Container()\nioc_container.register(A) # no need to specify label here\nioc_container.register(B) # but you can overwrite it if you want\n\nb = ioc_container.resolve(\"b\")\nprint(b.b()) # -> \"a b\"\n```\n\nMore examples will be available in `./examples`\n\n\n# Errors\n\n\n- `sinj.DependencyNotFoundError` - thrown on `resolve` when dependency is not found for a given label (and it is not optional).\n- `sinj.CircularDependencyError` - thrown on `resolve` when circular dependency is detected.\n- `sinj.DependencyConflictError` - thrown on `register` or `inject` when the container already has something by the label.\n- `sinj.DependencyNotMappedError` - thrown on `register` or `inject` when the class is not annotated and the label is not provided in register method.\n\n\n# Validating types\n\nYou have an option to pass a validator into `sinj.Container` to check injected types. `sinj` has a simple built in validator which is able to log warnings or raise errors. You can create more complicated validators if you want, it is just a class with `validate(self, instance, param: inspect.Parameter):` method:\n\n```python\n\nclass TypeValidator:\n    def __init__(self, log_warning=True, raise_error=False):\n        self._log_warning = log_warning\n        self._raise_error = raise_error\n\n    def validate(self, instance, param: inspect.Parameter):\n        err_msg = self._get_err_msg(instance, param)\n        if err_msg is None:\n            return\n\n        if self._log_warning:\n            logger.warning(err_msg)\n\n        if self._raise_error:\n            raise TypeValidatorError(err_msg)\n\n    def _get_err_msg(self, instance, param: inspect.Parameter):\n        if not hasattr(instance, \"__class__\"):\n            return f\"could not determine class of instance for {param.name}\"\n\n        if param.annotation == param.empty:\n            return None\n\n        if not inspect.isclass(param.annotation):\n            return f\"param annotated with a non-class for {param.name}\"\n\n        if not issubclass(instance.__class__, param.annotation):\n            return f\"instance is not derived from annotated type for {param.name}\"\n\n        return None\n\nioc_container = sinj.Container(validator=TypeValidator(True, True))\n```\n\n\n# Install\n\n\n### From [pypi.org](https://pypi.org/project/sinj/)\n\n```bash\npip install sinj\n```\n\n### From [repository](https://gitlab.com/mrsk/sinj)\n\n```bash\npip install git+https://gitlab.com/mrsk/sinj\n```\n\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2023 Marius Kavaliauskas  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "IoC container",
    "version": "0.3.1",
    "project_urls": {
        "Homepage": "https://gitlab.com/mrsk/sinj",
        "Issue Tracker": "https://gitlab.com/mrsk/sinj/-/issues",
        "Source Code": "https://gitlab.com/mrsk/sinj"
    },
    "split_keywords": [
        "ioc",
        "inverse-of-control",
        "injection",
        "dependency-injection",
        "dependencies-container"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9acc901ab84e6c20285cb31a3a34eefb386e406c3d0b116b324639c3f405c8d7",
                "md5": "93190c2d05916e862b991b5f4e41fe9a",
                "sha256": "a0d269a5ba1c4ba861573f52d4450e518819e26702035b9914f062913f971031"
            },
            "downloads": -1,
            "filename": "sinj-0.3.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "93190c2d05916e862b991b5f4e41fe9a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 7393,
            "upload_time": "2023-09-08T14:36:03",
            "upload_time_iso_8601": "2023-09-08T14:36:03.544702Z",
            "url": "https://files.pythonhosted.org/packages/9a/cc/901ab84e6c20285cb31a3a34eefb386e406c3d0b116b324639c3f405c8d7/sinj-0.3.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1d3029ff4f662b0baae7b16fe556c151ba77222b270c5a2ed842e4ae2c9de83d",
                "md5": "edb035924bd5b81d0ff36f0ee8cb8131",
                "sha256": "d2ff35b7ceab568719149c7dedf785d64433942943c31e0d613baf3f984051ed"
            },
            "downloads": -1,
            "filename": "sinj-0.3.1.tar.gz",
            "has_sig": false,
            "md5_digest": "edb035924bd5b81d0ff36f0ee8cb8131",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 7197,
            "upload_time": "2023-09-08T14:36:05",
            "upload_time_iso_8601": "2023-09-08T14:36:05.455447Z",
            "url": "https://files.pythonhosted.org/packages/1d/30/29ff4f662b0baae7b16fe556c151ba77222b270c5a2ed842e4ae2c9de83d/sinj-0.3.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-09-08 14:36:05",
    "github": false,
    "gitlab": true,
    "bitbucket": false,
    "codeberg": false,
    "gitlab_user": "mrsk",
    "gitlab_project": "sinj",
    "lcname": "sinj"
}
        
Elapsed time: 8.17347s