kink


Namekink JSON
Version 0.8.0 PyPI version JSON
download
home_pagehttps://github.com/kodemore/kink
SummaryDependency injection for python.
upload_time2024-04-15 05:30:17
maintainerNone
docs_urlNone
authorDawid Kraczkowski
requires_python<4.0,>=3.8
licenseMIT
keywords kink dependency injection
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Kink ![PyPI](https://img.shields.io/pypi/v/kink) ![Linting and Tests](https://github.com/kodemore/kink/workflows/Linting%20and%20Tests/badge.svg?branch=master) [![codecov](https://codecov.io/gh/kodemore/kink/branch/master/graph/badge.svg)](https://codecov.io/gh/kodemore/kink) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
Dependency injection container made for python

## Features

- Easy to use interface
- Extensible with custom dependency resolvers
- Automatic dependency injection (Autowiring)
- Lightweight
- Support for async with asyncio


## Installation

### Pip

```shell
pip install kink
```

### Poetry
If you don't know poetry, I highly recommend visiting their [webpage](https://python-poetry.org)

```shell
poetry add kink
```

# Why using dependency injection in python?

## Short story 

Because python is a multi paradigm language and this should encourage 
you to use best OOP practices improving your workflow and your code and have more time
for your hobbies and families instead monkey-patching entire world.

## Long story

Dependency happens when one component (component might be a class, or a function) `A` uses other component 
`B`. We say than that `A` depends on `B`.

Instead hardcoding dependency inside your components and making your code tightly coupled
you are loosing it by providing(injecting) required behaviour either by subclassing or
plugging additional code. This is called `Inversion of Control` which keeps your code
oriented around behaviour rather than control. There are many benefits coming out of it:
- increased modularity
- better extensibility and flexibility
- it helps you understand higher concepts like event driven programming

This is where dependency injection comes in place. Dependency injection is a specific
style of inversion of control, which generally says instead hardcoding dependency pass
dependant object as a parameter to a method rather than having method creating it itself.
( who would thought it is so easy :)? ). It can go even further than that; when you pass
a dependency don't rely on a particular implementation rely on an abstraction (`Dependency Inversion Principle`).

So you might ask why do I need it? Here is couple reasons:

### Relying on the global state is evil

Coding is hard enough ( business requirements are changing all the time, deadlines are
shortening, clients wants more, there are so many unknowns you have to figure out), 
relying on unpredictable state makes it even harder:
- it might introduce potential bugs
- makes code harder to maintain
- concurrency becomes harder to achieve
- balancing mokey-patching well is a hard task

### Great, but now I have additional work I have to manage now all my dependencies write more code and deadlines are coming even closer!

True, that is why you should pick up Dependency Injection Container to do all this work 
for you. Kink gives you one decorator and simple `dict-like` object to bootstrap and manipulate
your container.
No need for manual work and manual dependency management. Give it a try and you will love it!

# Usage

To fully utilise the potential of kink it is recommended to bootstrap your initial dependencies
(config values, or instances of classes that are standalone, requires no other dependencies than themselves).
Some people prefer to keep it in `__init__.py` in the top module of your application, other
create separate `bootstrap.py` file for this purpose. Once all is setup the only step left 
is to decorate your classes/functions with `@inject` decorator.

## Bootstrapping/Adding services manually

### Adding *service* to di container

Dependency container is a dict-like object, adding new service to dependency container is as 
simple as the following example:

```python
from kink import di
from os import getenv

di["db_name"] = getenv("DB_NAME")
di["db_password"] = getenv("DB_PASSWORD")
```

### Adding *on-demand service* to dependency injection container

Kink also supports on-demand service creation. In order to define such a service, 
lambda function should be used: 

```python
from kink import di
from sqlite3 import connect

di["db_connection"] = lambda di: connect(di["db_name"])
```

In this scenario connection to database will not be established until service is requested.

### Adding factorised services to dependency injection

Factorised services are services that are instantiated every time they are requested.

```python
from kink import di
from sqlite3 import connect

di.factories["db_connection"] = lambda di: connect(di["db_name"])

connection_1 = di["db_connection"]
connection_2 = di["db_connection"]

connection_1 != connection_2
```

In the above example we defined factorised service `db_connection`, and below by accessing the service from di we created
two separate connection to database.


## Requesting services from dependency injection container

To access given service just reference it inside `di` like you would do this with
a normal dictionary, full example below:

```python
from kink import di
from sqlite3 import connect

# Bootstrapping
di["db_name"] = "test_db.db"
di["db_connection"] = lambda di: connect(di["db_name"])


# Getting a service
connection = di["db_connection"] # will return instance of sqlite3.Connection
assert connection == di["db_connection"] # True
```


## Autowiring dependencies

Autowiring is the ability of the container to automatically create and inject dependencies.
It detects dependencies of the component tries to search for references in the container
and if all references are present an instance of requested service is returned.

Autowiring system in kink works in two ways:
- matching argument's names
- matching argument's type annotation

### How dependencies are prioritised by autowiring mechanism

Autowiring mechanism priorities dependencies automatically, so when multiple
matches are found for the service this is how it works;
Firstly passed arguments are prioritied - if you pass arguments manually to the service
they will take precendence over anything else. Next argument's names are taken into
consideration and last but not least argument's type annotations.

### Matching argument's names

If you don't like type annotations or would like to take advantage of autowiring's 
precedence mechanism use this style.

This is a very simple mechanism we have already seen in previous examples. 
Autowiring system checks function argument's names and tries to search for 
services with the same names inside the container. 

### Matching argument's type annotations

If you are like me and like type annotations and use static analysis tools this is
a preferred way working with DI container. 

In this scenario names are ignored instead argument's type annotations are inspected
and looked up inside di container. This requires aliases when bootstrapping 
your services in DI container or simply adding them to container in the way that
its type is the key by which service is accessed. Please consider the following example:

```python
from kink import di, inject
from sqlite3 import connect, Connection


di["db_name"] = "test_db.db"
di[Connection] = lambda di: connect(di["db_name"])  # sqlite connection can be accessed by its type

@inject # Constructor injection will happen here
class UserRepository:
  def __init__(self, db: Connection): # `db` argument will be resolved because `Connection` instance is present in the container. 
    self.db = db

repo = di[UserRepository]
assert repo.db == di[Connection] # True
```

## Constructor injection
```python
from kink import inject, di
import MySQLdb

# Set dependencies
di["db_host"] = "localhost"
di["db_name"] = "test"
di["db_user"] = "user"
di["db_password"] = "password"
di["db_connection"] = lambda di: MySQLdb.connect(host=di["db_host"], user=di["db_user"], passwd=di["db_password"], db=di["db_name"])

@inject
class AbstractRepository:
    def __init__(self, db_connection):
        self.connection = db_connection


class UserRepository(AbstractRepository):
    ...


repository = di[UserRepository] # will retrieve instance of UserRepository from di container
repository.connection # mysql db connection is resolved and available to use.
```

When class is annotated by `inject` annotation it will be automatically added to the container for future use (eg autowiring).


## Services aliasing

When you register a service with `@inject` decorator you can attach your own alias name, please consider the following example:

```python
from kink import inject
from typing import Protocol

class IUserRepository(Protocol):
    ...

@inject(alias=IUserRepository)
class UserRepository:
    ...


assert di[IUserRepository] == di[UserRepository] # returns true
```

For more examples check [tests](/tests) directory

### Retrieving all instances with the same alias
Aliases in `kink` do not have to be unique, but by default when autowiring mechnism is called the service that
was registered first within given alias will be returned. If for some reason you would like to retrieve all
services that alias to the same name (eg implementing strategy pattern), `kink` provides a useful functionality
for doing so. Please consider the following example:

```python
from kink import inject
from typing import Protocol, List

class IUserRepository(Protocol):
    ...

@inject(alias=IUserRepository)
class MongoUserRepository:
    ...

@inject(alias=IUserRepository)
class MySQLUserRepository:
    ...

@inject()
class UserRepository:
    def __init__(self, repos: List[IUserRepository]) -> None: # all services that alias to IUserRepository will be passed here
        self._repos = repos
        
    def store_to_mysql(self, user: ...):
        self._repos[1].store(user)
    
    def store_to_mongo(self, user: ...):
        self._repos[0].store(user)
```

## Clearing di cache

Sometimes it might come handy to clear cached services in di container. Simple way of 
doing this is calling `di.clear_cache()` method like in the following example.

```python
from kink import inject, di

... # set and accesss your services

di.clear_cache() # this will clear cache of all services inside di container that are not factorised services
```

## Integration with FastAPI

```python
from fastapi import APIRouter, Depends, status
from fastapi.responses import JSONResponse, Response
from kink import di

router = APIRouter()

# register service in the DI container
di[ClientService] = ClientService()

@router.post(
    "/clients",
    response_model=ClientDTO,
    responses={400: {"model": APIErrorMessage}, 500: {"model": APIErrorMessage}},
    tags=["clients"],
)
async def create_client(
    request: CreateClientDTO, service: ClientService = Depends(lambda: di[ClientService])
) -> JSONResponse:
    result = service.create(request)
    return JSONResponse(content=result.dict(), status_code=status.HTTP_201_CREATED)
```

A complete example, together with tests you can find it [here](https://github.com/szymon6927/hexagonal-architecture-python
).

# Articles on Kink

- [https://www.netguru.com/codestories/dependency-injection-with-python-make-it-easy](https://www.netguru.com/codestories/dependency-injection-with-python-make-it-easy)


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/kodemore/kink",
    "name": "kink",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": "kink, dependency injection",
    "author": "Dawid Kraczkowski",
    "author_email": "dawid.kraczkowski@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/29/e9/9a05eaa4eba7d68d6d81a1a5b1f373a1475f51acf85a0884d81d1994661a/kink-0.8.0.tar.gz",
    "platform": null,
    "description": "# Kink ![PyPI](https://img.shields.io/pypi/v/kink) ![Linting and Tests](https://github.com/kodemore/kink/workflows/Linting%20and%20Tests/badge.svg?branch=master) [![codecov](https://codecov.io/gh/kodemore/kink/branch/master/graph/badge.svg)](https://codecov.io/gh/kodemore/kink) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\nDependency injection container made for python\n\n## Features\n\n- Easy to use interface\n- Extensible with custom dependency resolvers\n- Automatic dependency injection (Autowiring)\n- Lightweight\n- Support for async with asyncio\n\n\n## Installation\n\n### Pip\n\n```shell\npip install kink\n```\n\n### Poetry\nIf you don't know poetry, I highly recommend visiting their [webpage](https://python-poetry.org)\n\n```shell\npoetry add kink\n```\n\n# Why using dependency injection in python?\n\n## Short story \n\nBecause python is a multi paradigm language and this should encourage \nyou to use best OOP practices improving your workflow and your code and have more time\nfor your hobbies and families instead monkey-patching entire world.\n\n## Long story\n\nDependency happens when one component (component might be a class, or a function) `A` uses other component \n`B`. We say than that `A` depends on `B`.\n\nInstead hardcoding dependency inside your components and making your code tightly coupled\nyou are loosing it by providing(injecting) required behaviour either by subclassing or\nplugging additional code. This is called `Inversion of Control` which keeps your code\noriented around behaviour rather than control. There are many benefits coming out of it:\n- increased modularity\n- better extensibility and flexibility\n- it helps you understand higher concepts like event driven programming\n\nThis is where dependency injection comes in place. Dependency injection is a specific\nstyle of inversion of control, which generally says instead hardcoding dependency pass\ndependant object as a parameter to a method rather than having method creating it itself.\n( who would thought it is so easy :)? ). It can go even further than that; when you pass\na dependency don't rely on a particular implementation rely on an abstraction (`Dependency Inversion Principle`).\n\nSo you might ask why do I need it? Here is couple reasons:\n\n### Relying on the global state is evil\n\nCoding is hard enough ( business requirements are changing all the time, deadlines are\nshortening, clients wants more, there are so many unknowns you have to figure out), \nrelying on unpredictable state makes it even harder:\n- it might introduce potential bugs\n- makes code harder to maintain\n- concurrency becomes harder to achieve\n- balancing mokey-patching well is a hard task\n\n### Great, but now I have additional work I have to manage now all my dependencies write more code and deadlines are coming even closer!\n\nTrue, that is why you should pick up Dependency Injection Container to do all this work \nfor you. Kink gives you one decorator and simple `dict-like` object to bootstrap and manipulate\nyour container.\nNo need for manual work and manual dependency management. Give it a try and you will love it!\n\n# Usage\n\nTo fully utilise the potential of kink it is recommended to bootstrap your initial dependencies\n(config values, or instances of classes that are standalone, requires no other dependencies than themselves).\nSome people prefer to keep it in `__init__.py` in the top module of your application, other\ncreate separate `bootstrap.py` file for this purpose. Once all is setup the only step left \nis to decorate your classes/functions with `@inject` decorator.\n\n## Bootstrapping/Adding services manually\n\n### Adding *service* to di container\n\nDependency container is a dict-like object, adding new service to dependency container is as \nsimple as the following example:\n\n```python\nfrom kink import di\nfrom os import getenv\n\ndi[\"db_name\"] = getenv(\"DB_NAME\")\ndi[\"db_password\"] = getenv(\"DB_PASSWORD\")\n```\n\n### Adding *on-demand service* to dependency injection container\n\nKink also supports on-demand service creation. In order to define such a service, \nlambda function should be used: \n\n```python\nfrom kink import di\nfrom sqlite3 import connect\n\ndi[\"db_connection\"] = lambda di: connect(di[\"db_name\"])\n```\n\nIn this scenario connection to database will not be established until service is requested.\n\n### Adding factorised services to dependency injection\n\nFactorised services are services that are instantiated every time they are requested.\n\n```python\nfrom kink import di\nfrom sqlite3 import connect\n\ndi.factories[\"db_connection\"] = lambda di: connect(di[\"db_name\"])\n\nconnection_1 = di[\"db_connection\"]\nconnection_2 = di[\"db_connection\"]\n\nconnection_1 != connection_2\n```\n\nIn the above example we defined factorised service `db_connection`, and below by accessing the service from di we created\ntwo separate connection to database.\n\n\n## Requesting services from dependency injection container\n\nTo access given service just reference it inside `di` like you would do this with\na normal dictionary, full example below:\n\n```python\nfrom kink import di\nfrom sqlite3 import connect\n\n# Bootstrapping\ndi[\"db_name\"] = \"test_db.db\"\ndi[\"db_connection\"] = lambda di: connect(di[\"db_name\"])\n\n\n# Getting a service\nconnection = di[\"db_connection\"] # will return instance of sqlite3.Connection\nassert connection == di[\"db_connection\"] # True\n```\n\n\n## Autowiring dependencies\n\nAutowiring is the ability of the container to automatically create and inject dependencies.\nIt detects dependencies of the component tries to search for references in the container\nand if all references are present an instance of requested service is returned.\n\nAutowiring system in kink works in two ways:\n- matching argument's names\n- matching argument's type annotation\n\n### How dependencies are prioritised by autowiring mechanism\n\nAutowiring mechanism priorities dependencies automatically, so when multiple\nmatches are found for the service this is how it works;\nFirstly passed arguments are prioritied - if you pass arguments manually to the service\nthey will take precendence over anything else. Next argument's names are taken into\nconsideration and last but not least argument's type annotations.\n\n### Matching argument's names\n\nIf you don't like type annotations or would like to take advantage of autowiring's \nprecedence mechanism use this style.\n\nThis is a very simple mechanism we have already seen in previous examples. \nAutowiring system checks function argument's names and tries to search for \nservices with the same names inside the container. \n\n### Matching argument's type annotations\n\nIf you are like me and like type annotations and use static analysis tools this is\na preferred way working with DI container. \n\nIn this scenario names are ignored instead argument's type annotations are inspected\nand looked up inside di container. This requires aliases when bootstrapping \nyour services in DI container or simply adding them to container in the way that\nits type is the key by which service is accessed. Please consider the following example:\n\n```python\nfrom kink import di, inject\nfrom sqlite3 import connect, Connection\n\n\ndi[\"db_name\"] = \"test_db.db\"\ndi[Connection] = lambda di: connect(di[\"db_name\"])  # sqlite connection can be accessed by its type\n\n@inject # Constructor injection will happen here\nclass UserRepository:\n  def __init__(self, db: Connection): # `db` argument will be resolved because `Connection` instance is present in the container. \n    self.db = db\n\nrepo = di[UserRepository]\nassert repo.db == di[Connection] # True\n```\n\n## Constructor injection\n```python\nfrom kink import inject, di\nimport MySQLdb\n\n# Set dependencies\ndi[\"db_host\"] = \"localhost\"\ndi[\"db_name\"] = \"test\"\ndi[\"db_user\"] = \"user\"\ndi[\"db_password\"] = \"password\"\ndi[\"db_connection\"] = lambda di: MySQLdb.connect(host=di[\"db_host\"], user=di[\"db_user\"], passwd=di[\"db_password\"], db=di[\"db_name\"])\n\n@inject\nclass AbstractRepository:\n    def __init__(self, db_connection):\n        self.connection = db_connection\n\n\nclass UserRepository(AbstractRepository):\n    ...\n\n\nrepository = di[UserRepository] # will retrieve instance of UserRepository from di container\nrepository.connection # mysql db connection is resolved and available to use.\n```\n\nWhen class is annotated by `inject` annotation it will be automatically added to the container for future use (eg autowiring).\n\n\n## Services aliasing\n\nWhen you register a service with `@inject` decorator you can attach your own alias name, please consider the following example:\n\n```python\nfrom kink import inject\nfrom typing import Protocol\n\nclass IUserRepository(Protocol):\n    ...\n\n@inject(alias=IUserRepository)\nclass UserRepository:\n    ...\n\n\nassert di[IUserRepository] == di[UserRepository] # returns true\n```\n\nFor more examples check [tests](/tests) directory\n\n### Retrieving all instances with the same alias\nAliases in `kink` do not have to be unique, but by default when autowiring mechnism is called the service that\nwas registered first within given alias will be returned. If for some reason you would like to retrieve all\nservices that alias to the same name (eg implementing strategy pattern), `kink` provides a useful functionality\nfor doing so. Please consider the following example:\n\n```python\nfrom kink import inject\nfrom typing import Protocol, List\n\nclass IUserRepository(Protocol):\n    ...\n\n@inject(alias=IUserRepository)\nclass MongoUserRepository:\n    ...\n\n@inject(alias=IUserRepository)\nclass MySQLUserRepository:\n    ...\n\n@inject()\nclass UserRepository:\n    def __init__(self, repos: List[IUserRepository]) -> None: # all services that alias to IUserRepository will be passed here\n        self._repos = repos\n        \n    def store_to_mysql(self, user: ...):\n        self._repos[1].store(user)\n    \n    def store_to_mongo(self, user: ...):\n        self._repos[0].store(user)\n```\n\n## Clearing di cache\n\nSometimes it might come handy to clear cached services in di container. Simple way of \ndoing this is calling `di.clear_cache()` method like in the following example.\n\n```python\nfrom kink import inject, di\n\n... # set and accesss your services\n\ndi.clear_cache() # this will clear cache of all services inside di container that are not factorised services\n```\n\n## Integration with FastAPI\n\n```python\nfrom fastapi import APIRouter, Depends, status\nfrom fastapi.responses import JSONResponse, Response\nfrom kink import di\n\nrouter = APIRouter()\n\n# register service in the DI container\ndi[ClientService] = ClientService()\n\n@router.post(\n    \"/clients\",\n    response_model=ClientDTO,\n    responses={400: {\"model\": APIErrorMessage}, 500: {\"model\": APIErrorMessage}},\n    tags=[\"clients\"],\n)\nasync def create_client(\n    request: CreateClientDTO, service: ClientService = Depends(lambda: di[ClientService])\n) -> JSONResponse:\n    result = service.create(request)\n    return JSONResponse(content=result.dict(), status_code=status.HTTP_201_CREATED)\n```\n\nA complete example, together with tests you can find it [here](https://github.com/szymon6927/hexagonal-architecture-python\n).\n\n# Articles on Kink\n\n- [https://www.netguru.com/codestories/dependency-injection-with-python-make-it-easy](https://www.netguru.com/codestories/dependency-injection-with-python-make-it-easy)\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Dependency injection for python.",
    "version": "0.8.0",
    "project_urls": {
        "Documentation": "https://github.com/kodemore/kink",
        "Homepage": "https://github.com/kodemore/kink",
        "Repository": "https://github.com/kodemore/kink"
    },
    "split_keywords": [
        "kink",
        " dependency injection"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "49fa4a00e57656eb30c71be7996ee6d95e4cc4958c19009a1d3481a81cfa99ce",
                "md5": "661b36d9431b00534277488dc4763c96",
                "sha256": "c0b959cd291e057a72c501ffc77498416ef5afd5f30476a7d5e6fc3be09001a5"
            },
            "downloads": -1,
            "filename": "kink-0.8.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "661b36d9431b00534277488dc4763c96",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 11204,
            "upload_time": "2024-04-15T05:30:15",
            "upload_time_iso_8601": "2024-04-15T05:30:15.632129Z",
            "url": "https://files.pythonhosted.org/packages/49/fa/4a00e57656eb30c71be7996ee6d95e4cc4958c19009a1d3481a81cfa99ce/kink-0.8.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "29e99a05eaa4eba7d68d6d81a1a5b1f373a1475f51acf85a0884d81d1994661a",
                "md5": "2749944947c9bf6077b52fc81986ba3b",
                "sha256": "5aa6dcb4c0abde9ed15c4f73e52f163802c91fd7d804b3e1e4e8e78b9cef48f2"
            },
            "downloads": -1,
            "filename": "kink-0.8.0.tar.gz",
            "has_sig": false,
            "md5_digest": "2749944947c9bf6077b52fc81986ba3b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 13038,
            "upload_time": "2024-04-15T05:30:17",
            "upload_time_iso_8601": "2024-04-15T05:30:17.591563Z",
            "url": "https://files.pythonhosted.org/packages/29/e9/9a05eaa4eba7d68d6d81a1a5b1f373a1475f51acf85a0884d81d1994661a/kink-0.8.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-15 05:30:17",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "kodemore",
    "github_project": "kink",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "kink"
}
        
Elapsed time: 0.21719s