Skip to main content

Dependency injection library

Project description

Opyoid

CI codecov

Dependency injection library using typings, to easily manage large applications.

This project is inspired from Guice.

Installation

Run pip install opyoid to install from PyPI.

Run pip install . to install from sources.

This project follows the (Semantic Versioning Specification)[https://semver.org/]. All breaking changes are described in the Changelog.

Usage

Simple Injection

from opyoid import Module, Injector


class MyClass:
    pass


class MyParentClass:
    def __init__(self, my_param: MyClass):
        self.my_param = my_param


class MyModule(Module):
    def configure(self) -> None:
        self.bind(MyClass)
        self.bind(MyParentClass)


injector = Injector([MyModule()])
my_instance = injector.inject(MyParentClass)
assert isinstance(my_instance, MyParentClass)
assert isinstance(my_instance.my_param, MyClass)

If they are multiple bindings for the same class, the latest will be used.

Module

The module is used to group bindings related to a feature. You can include a module in another with install:

from opyoid import Module, Injector


class MyClass:
    pass


class MyModule(Module):
    def configure(self) -> None:
        self.bind(MyClass)


class MyParentClass:
    def __init__(self, my_param: MyClass):
        self.my_param = my_param


class MyParentModule(Module):
    def configure(self) -> None:
        self.install(MyModule())
        self.bind(MyParentClass)


injector = Injector([MyParentModule()])
my_instance = injector.inject(MyParentClass)
assert isinstance(my_instance, MyParentClass)
assert isinstance(my_instance.my_param, MyClass)

Binding Subclasses

from opyoid import Module, Injector


class MyClass:
    pass


class MySubClass(MyClass):
    pass


class MyModule(Module):
    def configure(self) -> None:
        self.bind(MyClass, MySubClass)

injector = Injector([MyModule()])
my_instance = injector.inject(MyClass)
assert isinstance(my_instance, MySubClass)

Binding Instances

from opyoid import Module, Injector


class MyClass:
    def __init__(self, my_param: str):
        self.my_param = my_param

my_instance = MyClass("hello")


class MyModule(Module):
    def configure(self) -> None:
        self.bind(MyClass, to_instance=my_instance)


injector = Injector([MyModule()])
injected_instance = injector.inject(MyClass)
assert my_instance is injected_instance

Binding scopes

When binding a class, you can choose the scope in which it will be instantiated. This will only have an effect when binding classes, not instances.

Singleton Scope

By default, all classes are instantiated in a Singleton scope. This means that only one instance of each class will be created, and it will be shared between all classes requiring it.

from opyoid import Module, Injector, SingletonScope


class MyClass:
    pass


class MyParentClass:
    def __init__(self, my_param: MyClass):
        self.my_param = my_param


class MyModule(Module):
    def configure(self) -> None:
        self.bind(MyClass, scope=SingletonScope)
        self.bind(MyParentClass, scope=SingletonScope)

injector = Injector([MyModule()])
instance_1 = injector.inject(MyClass)
instance_2 = injector.inject(MyClass)
parent_instance = injector.inject(MyParentClass)
assert instance_1 is instance_2
assert instance_1 is parent_instance.my_param

PerLookup Scope

If you use the per lookup scope, a new instance will be created every time each class is injected.

from opyoid import Module, Injector, PerLookupScope


class MyClass:
    pass


class MyParentClass:
    def __init__(self, my_param: MyClass):
        self.my_param = my_param


class MyModule(Module):
    def configure(self) -> None:
        self.bind(MyClass, scope=PerLookupScope)
        self.bind(MyParentClass)

injector = Injector([MyModule()])
instance_1 = injector.inject(MyClass)
instance_2 = injector.inject(MyClass)
parent_instance = injector.inject(MyParentClass)
assert instance_1 is not instance_2
assert instance_1 is not parent_instance.my_param

Thread Scope

This scope only creates a new instance the first time that the class is injected in the current thread. There will only be one instance of each class in each thread, and two instances injected from different threads will be different objects.

from threading import Thread

from opyoid import Module, Injector, ThreadScope


class MyClass:
    pass


class MyModule(Module):
    def configure(self) -> None:
        self.bind(MyClass, scope=ThreadScope)

injector = Injector([MyModule()])
instance_1 = injector.inject(MyClass)
instance_2 = injector.inject(MyClass)

def thread_target():
    instance_3 = injector.inject(MyClass)
    assert instance_1 is not instance_3

Thread(target=thread_target).start()

assert instance_1 is instance_2

Bindings without Module

If you prefer, you can add bindings to your injector without creating a Module class (or using both).

from opyoid import Module, ClassBinding, Injector


class MyClass:
    pass


class MyParentClass:
    def __init__(self, my_param: MyClass):
        self.my_param = my_param


class MyModule(Module):
    def configure(self) -> None:
        self.bind(MyClass)


injector = Injector([MyModule()], [ClassBinding(MyParentClass)])
my_instance = injector.inject(MyParentClass)
assert isinstance(my_instance, MyParentClass)
assert isinstance(my_instance.my_param, MyClass)

The same options of Module.bind are available when using bindings:

from opyoid import ClassBinding, InstanceBinding, PerLookupScope


class MyClass:
    pass


class MySubClass(MyClass):
    pass

my_instance = MyClass()

ClassBinding(MyClass)  # binding a class to itself
ClassBinding(MyClass, MySubClass)  # binding a class to a subclass
ClassBinding(MyClass, scope=PerLookupScope)  # specifying scope
InstanceBinding(MyClass, my_instance)  # binding an instance
ClassBinding(MyClass, annotation="my_annotation")  # binding a class to itself with an annotation
InstanceBinding(MyClass, my_instance, annotation="my_annotation")  # binding an instance with an annotation

Injecting Type

If no explicit binding is defined, the last class binding will be used to inject a type:

from typing import Type

from opyoid import Module, Injector

class MyClass:
    pass

class SubClass(MyClass):
    pass

class MyParentClass:
    def __init__(self, my_param: Type[MyClass]):
        self.my_param = my_param

my_instance = MyClass()

class MyModule(Module):
    def configure(self) -> None:
        self.bind(MyClass)
        self.bind(MyClass, SubClass)
        self.bind(MyClass, to_instance=my_instance)
        self.bind(MyParentClass)


injector = Injector([MyModule()])
parent_instance = injector.inject(MyParentClass)
assert isinstance(my_instance, MyParentClass)
assert my_instance.my_param is SubClass

Dataclasses

opyoid can inject classes and parameters defined with the attrs library and python data classes.

Notes about Generics

  • The only supported generic types are List, Set, Tuple, Optional and Type (and any combination of them). Other generics must be bound explicitly (e.g. you must bind a dict to Dict[str, MyClass] if you want to inject it).
  • Be careful when using generics, the bindings will only be used if the type matches exactly. For example, you cannot implicitly bind MyClass[T] to inject MyClass, or MyClass[str] to inject MyClass[T]. You need to bind something to MyClass[str] to be able to inject it.

Advanced usage

More advanced features and examples are available in the ./docs folder.

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

opyoid-0.5.0.tar.gz (18.7 kB view details)

Uploaded Source

Built Distribution

opyoid-0.5.0-py3-none-any.whl (37.2 kB view details)

Uploaded Python 3

File details

Details for the file opyoid-0.5.0.tar.gz.

File metadata

  • Download URL: opyoid-0.5.0.tar.gz
  • Upload date:
  • Size: 18.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/47.1.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.8.5

File hashes

Hashes for opyoid-0.5.0.tar.gz
Algorithm Hash digest
SHA256 794fc909c39cd9dc74dcfce09f20e60b6df023b7e9a7f35e52fcae706362d491
MD5 0640536e899b87b1f904b40be61bb1e2
BLAKE2b-256 29d6598568ea57b5cde291392b1c0f1400786ef3971d38a0a2b8bff48a3c1e0a

See more details on using hashes here.

File details

Details for the file opyoid-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: opyoid-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 37.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/47.1.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.8.5

File hashes

Hashes for opyoid-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 508c3c6572597ab12ab11b9ce243a4813c14056818c20e7a3c5fdfa7ad308754
MD5 c4f60bc7583e8560db3870843dd54d67
BLAKE2b-256 32905b7432b2087633ff3075bfa6ece592c75894987f9f71e2a697c414aced4b

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