Skip to main content

Cute DI framework with scopes and agreeable API

Project description

Dishka (from russian "cute DI")

PyPI version Supported versions downloads license GitHub Actions Workflow Status Doc Telegram

Cute DI framework with scopes and agreeable API.

📚 Documentation

Purpose

This library is targeting to provide only an IoC-container but make it really useful. If you are tired manually passing objects to create others objects which are only used to create more objects - we have a solution. Not all project require an IoC-container, but check what we have.

Unlike other instruments we are not trying to solve tasks not related to dependency injection. We want to keep DI in place, not soiling you code with global variables and additional specifiers in all places.

Main ideas:

  • Scopes. Any object can have lifespan of the whole app, single request or even more fractionally. Many frameworks do not have scopes or have only 2 of them. Here you can have as many scopes as you need.
  • Finalization. Some dependencies like database connections must be not only created, but carefully released. Many framework lack this essential feature
  • Modular providers. Instead of creating lots of separate functions or contrariwise a big single class, you can split your factories into several classes, which makes them simpler reusable.
  • Clean dependencies. You do not need to add custom markers to the code of dependencies so to allow library to see them. All customization is done within providers code and only borders of scopes have to deal with library API.
  • Simple API. You need minimum of objects to start using library. You can easily integrate it with your task framework, examples provided.
  • Speed. It is fast enough so you not to worry about. It is even faster than many of the analogs.

See more in technical requirements

Quickstart

  1. Install dishka
pip install dishka
  1. Create Provider instance. It is only used to setup all factories providing your objects.
from dishka import Provider

provider = Provider()
  1. Register functions which provide dependencies. Do not forget to place correct typehints for parameters and result. We use scope=Scope.APP for dependencies which are created only once in application lifetime, and scope=Scope.REQUEST for those which should be recreated for each processing request/event/etc.
from dishka import Provider, Scope

def get_a() -> A:
   return A()

def get_b(a: A) -> B:
   return B(a)

provider = Provider()
provider.provide(get_a, scope=Scope.APP)
provider.provide(get_b, scope=Scope.REQUEST)

This can be also rewritten using classes:

from dishka import provide, Provider, Scope

class MyProvider(Provider):
  @provide(scope=Scope.APP)
  def get_a(self) -> A:
     return A()
  
  @provide(scope=Scope.REQUEST)
  def get_b(self, a: A) -> B:
     return B(a)

provider = MyProvider()
  1. Create Container instance passing providers, and step into APP scope. Container holds dependencies cache and is used to retrieve them. Here, you can use .get method to access APP-scoped dependencies:
from dishka import make_container
container = make_container(provider)  # it has Scope.APP
a = container.get(A)  # `A` has Scope.APP, so it is accessible here
  1. You can enter and exit REQUEST scope multiple times after that:
from dishka import make_container
container = make_container(provider)
with container() as request_container:
    b = request_container.get(B)  # `B` has Scope.REQUEST
    a = request_container.get(A)  # `A` is accessible here too

with container() as request_container:
    b = request_container.get(B)  # another instance of `B`
    a = request_container.get(A)  # the same instance of `A`
  1. Close container in the end:
container.close()
  1. If you are using supported framework add decorators and middleware for it.
from dishka.integrations.fastapi import (
    FromDishka, inject, setup_dishka,
)

@router.get("/")
@inject
async def index(a: FromDishka[A]) -> str:
    ...

...

setup_dishka(container, app)

Concepts

Dependency is what you need for some part of your code to work. They are just object which you do not create in place and probably want to replace some day. At least for tests. Some of them can live while you application is running, others are destroyed and created on each request. Dependencies can depend on other objects, which are their dependencies.

Scope is a lifespan of a dependency. Standard scopes are (without skipped ones):

APP -> REQUEST -> ACTION -> STEP.

You decide when to enter and exit them, but it is done one by one. You set a scope for your dependency when you configure how to create it. If the same dependency is requested multiple time within one scope without leaving it, then by default the same instance is returned.

If you are developing web application, you would enter APP scope on startup, and you would REQUEST scope in each HTTP-request.

You can provide your own Scopes class if you are not satisfied with standard flow.

Container is what you use to get your dependency. You just call .get(SomeType) and it finds a way to get you an instance of that type. It does not create things itself, but manages their lifecycle and caches. It delegates objects creation to providers which are passed during creation.

Provider is a collection of functions which really provide some objects. Provider itself is a class with some attributes and methods. Each of them is either result of provide, alias or decorate. They can be used as provider methods, functions to assign attributes or method decorators.

@provide can be used as a decorator for some method. This method will be called when corresponding dependency has to be created. Name of the method is not important: just check that it is different form other Provider attributes. Type hints do matter: they show what this method creates and what does it require. All method parameters are treated as other dependencies and created using container.

If provide is used with some class then that class itself is treated as a factory (__init__ is analyzed for parameters). But do not forget to assign that call to some attribute otherwise it will be ignored.

Component - is an isolated group of providers within the same container identified by a string. When dependency is requested it is searched only within the same component as its dependant, unless it is declared explicitly.

This allows you to have multiple parts of application build separately without need to think if the use same types.

Tips

  • Add method and mark it with @provide decorator. It can be sync or async method returning some value.

    class MyProvider(Provider):
        @provide(scope=Scope.REQUEST)
        def get_a(self) -> A:
            return A()
    
  • Want some finalization when exiting the scope? Make that method generator:

    class MyProvider(Provider):
        @provide(scope=Scope.REQUEST)
        def get_a(self) -> Iterable[A]:
            a = A()
            yield a
            a.close()
    
  • Do not have any specific logic and just want to create class using its __init__? then add a provider attribute using provide as function passing that class.

    class MyProvider(Provider):
        a = provide(A, scope=Scope.REQUEST)
    
  • Want to create a child class instance when parent is requested? add a source attribute to provide function with a parent class while passing child as a first parameter

    class MyProvider(Provider):
        a = provide(source=AChild, scope=Scope.REQUEST, provides=A)
    
  • Having multiple interfaces which can be created as a same class? Use AnyOf:

    from dishka import AnyOf
    
    class MyProvider(Provider):
        @provide
        def p(self) -> AnyOf[A, AProtocol]:
            return A()
    

    Use alias if you want to add them in another Provider:

    class MyProvider2(Provider):
        p = alias(source=A, provides=AProtocol)
    

    In both cases it works the same way as

    class MyProvider2(Provider):
        @provide(scope=<Scope of A>)
        def p(self, a: A) -> AProtocol:
            return a
    
  • Want to apply decorator pattern and do not want to alter existing provide method? Use decorate. It will construct object using earlie defined provider and then pass it to your decorator before returning from the container.

      class MyProvider(Provider):
          @decorate
          def decorate_a(self, a: A) -> A:
              return ADecorator(a)
    

    Decorator function can also have additional parameters.

  • Want to go async? Make provide methods asynchronous. Create async container. Use async with and await get calls:

class MyProvider(Provider):
   @provide(scope=Scope.APP)
   async def get_a(self) -> A:
      return A()

container = make_async_container(MyProvider())
a = await container.get(A)
  • Having some data connected with scope which you want to use when solving dependencies? Set it when entering scope. These classes can be used as parameters of your provide methods. But you need to specify them in provider as retrieved form context.
from dishka import from_context, Provider, provide, Scope

class MyProvider(Provider):
    scope = Scope.REQUEST

    app = from_context(App, scope=Scope.APP)
    request = from_context(RequestClass)

    @provide
    def get_a(self, request: RequestClass, app: App) -> A:
        ...

container = make_container(MyProvider(), context={App: app})
with container(context={RequestClass: request_instance}) as request_container:
    pass
  • Having too many dependencies? Or maybe want to replace only part of them in tests keeping others? Create multiple Provider classes
container = make_container(MyProvider(), OtherProvider())
  • Tired of providing scope for each dependency? Set it inside your Provider class and all dependencies with no scope will use it.
class MyProvider(Provider):
   scope = Scope.APP

   @provide
   async def get_a(self) -> A:
      return A()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dishka-1.3.0.tar.gz (50.0 kB view details)

Uploaded Source

Built Distribution

dishka-1.3.0-py3-none-any.whl (66.6 kB view details)

Uploaded Python 3

File details

Details for the file dishka-1.3.0.tar.gz.

File metadata

  • Download URL: dishka-1.3.0.tar.gz
  • Upload date:
  • Size: 50.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.11.9

File hashes

Hashes for dishka-1.3.0.tar.gz
Algorithm Hash digest
SHA256 07c12cf87517f86d55e113701a4ceb816af4f46ae97929b395d92a0e4b9d6aec
MD5 9013db68a1a2dec2dcd8250dbb50db6a
BLAKE2b-256 37c0af4aac6b287c5f2aa0402c73ed437862d29e1282e710c0451dc92e95ceda

See more details on using hashes here.

File details

Details for the file dishka-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: dishka-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 66.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.11.9

File hashes

Hashes for dishka-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 37d534f9d4cb60df1f3ea19a193d60242a509433abb3d94dbefe62b38804ff7a
MD5 a810ff0c8cb1dd0df46aa74c159176b1
BLAKE2b-256 682d7b52f200b66e9286642fcfca66cc7e066d796ffd77479a26fb577dbb68e1

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page