injector


Nameinjector JSON
Version 0.21.0 PyPI version JSON
download
home_pagehttps://github.com/alecthomas/injector
SummaryInjector - Python dependency injection framework, inspired by Guice
upload_time2023-07-27 00:42:25
maintainer
docs_urlNone
authorAlec Thomas
requires_python
licenseBSD
keywords dependency injection di dependency injection framework inversion of control ioc inversion of control container
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            Injector - Python dependency injection framework, inspired by Guice
===================================================================

|image| |Coverage Status|

Introduction
------------

While dependency injection is easy to do in Python due to its support
for keyword arguments, the ease with which objects can be mocked and its
dynamic nature, a framework for assisting in this process can remove a
lot of boiler-plate from larger applications. That’s where Injector can
help. It automatically and transitively provides dependencies for you.
As an added benefit, Injector encourages nicely compartmentalised code
through the use of modules.

If you’re not sure what dependency injection is or you’d like to learn
more about it see:

-  `The Clean Code Talks - Don’t Look For Things! (a talk by Miško
   Hevery) <https://www.youtube.com/watch?v=RlfLCWKxHJ0>`__
-  `Inversion of Control Containers and the Dependency Injection pattern
   (an article by Martin
   Fowler) <https://martinfowler.com/articles/injection.html>`__

The core values of Injector are:

-  Simplicity - while being inspired by Guice, Injector does not
   slavishly replicate its API. Providing a Pythonic API trumps
   faithfulness. Additionally some features are omitted because
   supporting them would be cumbersome and introduce a little bit too
   much “magic” (member injection, method injection).

   Connected to this, Injector tries to be as nonintrusive as possible.
   For example while you may declare a class’ constructor to expect some
   injectable parameters, the class’ constructor remains a standard
   constructor – you may instantiate the class just the same manually,
   if you want.

-  No global state – you can have as many
   `Injector <https://injector.readthedocs.io/en/latest/api.html#injector.Injector>`__
   instances as you like, each with a different configuration and each
   with different objects in different scopes. Code like this won’t work
   for this very reason:

   .. code:: python

        class MyClass:
            @inject
            def __init__(t: SomeType):
                # ...

        MyClass()

   This is simply because there’s no global ``Injector`` to use. You
   need to be explicit and use
   `Injector.get <https://injector.readthedocs.io/en/latest/api.html#injector.Injector.get>`__,
   `Injector.create_object <https://injector.readthedocs.io/en/latest/api.html#injector.Injector.create_object>`__
   or inject ``MyClass`` into the place that needs it.

-  Cooperation with static type checking infrastructure – the API
   provides as much static type safety as possible and only breaks it
   where there’s no other option. For example the
   `Injector.get <https://injector.readthedocs.io/en/latest/api.html#injector.Injector.get>`__
   method is typed such that ``injector.get(SomeType)`` is statically
   declared to return an instance of ``SomeType``, therefore making it
   possible for tools such as `mypy <https://github.com/python/mypy>`__
   to type-check correctly the code using it.

-  The client code only knows about dependency injection to the extent
   it needs – 
   ```inject`` <https://injector.readthedocs.io/en/latest/api.html#injector.inject>`__,
   ```Inject`` <https://injector.readthedocs.io/en/latest/api.html#injector.Inject>`__
   and
   ```NoInject`` <https://injector.readthedocs.io/en/latest/api.html#injector.NoInject>`__
   are simple markers that don’t really do anything on their own and
   your code can run just fine without Injector orchestrating things.

How to get Injector?
~~~~~~~~~~~~~~~~~~~~

-  GitHub (code repository, issues):
   https://github.com/alecthomas/injector

-  PyPI (installable, stable distributions):
   https://pypi.org/project/injector/. You can install it using pip:

   .. code:: bash

      pip install injector

-  Documentation: https://injector.readthedocs.org

-  Change log: https://injector.readthedocs.io/en/latest/changelog.html

Injector works with CPython 3.7+ and PyPy 3 implementing Python 3.7+.

A Quick Example
---------------

.. code:: python

   >>> from injector import Injector, inject
   >>> class Inner:
   ...     def __init__(self):
   ...         self.forty_two = 42
   ...
   >>> class Outer:
   ...     @inject
   ...     def __init__(self, inner: Inner):
   ...         self.inner = inner
   ...
   >>> injector = Injector()
   >>> outer = injector.get(Outer)
   >>> outer.inner.forty_two
   42

Or with ``dataclasses`` if you like:

.. code:: python

   from dataclasses import dataclass
   from injector import Injector, inject
   class Inner:
       def __init__(self):
           self.forty_two = 42

   @inject
   @dataclass
   class Outer:
       inner: Inner

   injector = Injector()
   outer = injector.get(Outer)
   print(outer.inner.forty_two)  # Prints 42

A Full Example
--------------

Here’s a full example to give you a taste of how Injector works:

.. code:: python

   >>> from injector import Module, provider, Injector, inject, singleton

We’ll use an in-memory SQLite database for our example:

.. code:: python

   >>> import sqlite3

And make up an imaginary ``RequestHandler`` class that uses the SQLite
connection:

.. code:: python

   >>> class RequestHandler:
   ...   @inject
   ...   def __init__(self, db: sqlite3.Connection):
   ...     self._db = db
   ...
   ...   def get(self):
   ...     cursor = self._db.cursor()
   ...     cursor.execute('SELECT key, value FROM data ORDER by key')
   ...     return cursor.fetchall()

Next, for the sake of the example, we’ll create a configuration type:

.. code:: python

   >>> class Configuration:
   ...     def __init__(self, connection_string):
   ...         self.connection_string = connection_string

Next, we bind the configuration to the injector, using a module:

.. code:: python

   >>> def configure_for_testing(binder):
   ...     configuration = Configuration(':memory:')
   ...     binder.bind(Configuration, to=configuration, scope=singleton)

Next we create a module that initialises the DB. It depends on the
configuration provided by the above module to create a new DB
connection, then populates it with some dummy data, and provides a
``Connection`` object:

.. code:: python

   >>> class DatabaseModule(Module):
   ...   @singleton
   ...   @provider
   ...   def provide_sqlite_connection(self, configuration: Configuration) -> sqlite3.Connection:
   ...     conn = sqlite3.connect(configuration.connection_string)
   ...     cursor = conn.cursor()
   ...     cursor.execute('CREATE TABLE IF NOT EXISTS data (key PRIMARY KEY, value)')
   ...     cursor.execute('INSERT OR REPLACE INTO data VALUES ("hello", "world")')
   ...     return conn

(Note how we have decoupled configuration from our database
initialisation code.)

Finally, we initialise an ``Injector`` and use it to instantiate a
``RequestHandler`` instance. This first transitively constructs a
``sqlite3.Connection`` object, and the Configuration dictionary that it
in turn requires, then instantiates our ``RequestHandler``:

.. code:: python

   >>> injector = Injector([configure_for_testing, DatabaseModule()])
   >>> handler = injector.get(RequestHandler)
   >>> tuple(map(str, handler.get()[0]))  # py3/py2 compatibility hack
   ('hello', 'world')

We can also verify that our ``Configuration`` and ``SQLite`` connections
are indeed singletons within the Injector:

.. code:: python

   >>> injector.get(Configuration) is injector.get(Configuration)
   True
   >>> injector.get(sqlite3.Connection) is injector.get(sqlite3.Connection)
   True

You’re probably thinking something like: “this is a large amount of work
just to give me a database connection”, and you are correct; dependency
injection is typically not that useful for smaller projects. It comes
into its own on large projects where the up-front effort pays for itself
in two ways:

1. Forces decoupling. In our example, this is illustrated by decoupling
   our configuration and database configuration.
2. After a type is configured, it can be injected anywhere with no
   additional effort. Simply ``@inject`` and it appears. We don’t really
   illustrate that here, but you can imagine adding an arbitrary number
   of ``RequestHandler`` subclasses, all of which will automatically
   have a DB connection provided.

Footnote
--------

This framework is similar to snake-guice, but aims for simplification.

© Copyright 2010-2013 to Alec Thomas, under the BSD license

.. |image| image:: https://github.com/alecthomas/injector/workflows/CI/badge.svg
   :target: https://github.com/alecthomas/injector/actions?query=workflow%3ACI+branch%3Amaster
.. |Coverage Status| image:: https://codecov.io/gh/alecthomas/injector/branch/master/graph/badge.svg
   :target: https://codecov.io/gh/alecthomas/injector



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/alecthomas/injector",
    "name": "injector",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "Dependency Injection,DI,Dependency Injection framework,Inversion of Control,IoC,Inversion of Control container",
    "author": "Alec Thomas",
    "author_email": "alec@swapoff.org",
    "download_url": "https://files.pythonhosted.org/packages/da/91/b6da45ee1251c136bda46c2e404e5a056fd47c9cda9d8857974eac9e2f4d/injector-0.21.0.tar.gz",
    "platform": "any",
    "description": "Injector - Python dependency injection framework, inspired by Guice\n===================================================================\n\n|image| |Coverage Status|\n\nIntroduction\n------------\n\nWhile dependency injection is easy to do in Python due to its support\nfor keyword arguments, the ease with which objects can be mocked and its\ndynamic nature, a framework for assisting in this process can remove a\nlot of boiler-plate from larger applications. That\u2019s where Injector can\nhelp. It automatically and transitively provides dependencies for you.\nAs an added benefit, Injector encourages nicely compartmentalised code\nthrough the use of modules.\n\nIf you\u2019re not sure what dependency injection is or you\u2019d like to learn\nmore about it see:\n\n-  `The Clean Code Talks - Don\u2019t Look For Things! (a talk by Mi\u0161ko\n   Hevery) <https://www.youtube.com/watch?v=RlfLCWKxHJ0>`__\n-  `Inversion of Control Containers and the Dependency Injection pattern\n   (an article by Martin\n   Fowler) <https://martinfowler.com/articles/injection.html>`__\n\nThe core values of Injector are:\n\n-  Simplicity - while being inspired by Guice, Injector does not\n   slavishly replicate its API. Providing a Pythonic API trumps\n   faithfulness. Additionally some features are omitted because\n   supporting them would be cumbersome and introduce a little bit too\n   much \u201cmagic\u201d (member injection, method injection).\n\n   Connected to this, Injector tries to be as nonintrusive as possible.\n   For example while you may declare a class\u2019 constructor to expect some\n   injectable parameters, the class\u2019 constructor remains a standard\n   constructor \u2013\u00a0you may instantiate the class just the same manually,\n   if you want.\n\n-  No global state \u2013 you can have as many\n   `Injector <https://injector.readthedocs.io/en/latest/api.html#injector.Injector>`__\n   instances as you like, each with a different configuration and each\n   with different objects in different scopes. Code like this won\u2019t work\n   for this very reason:\n\n   .. code:: python\n\n        class MyClass:\n            @inject\n            def __init__(t: SomeType):\n                # ...\n\n        MyClass()\n\n   This is simply because there\u2019s no global ``Injector`` to use. You\n   need to be explicit and use\n   `Injector.get <https://injector.readthedocs.io/en/latest/api.html#injector.Injector.get>`__,\n   `Injector.create_object <https://injector.readthedocs.io/en/latest/api.html#injector.Injector.create_object>`__\n   or inject ``MyClass`` into the place that needs it.\n\n-  Cooperation with static type checking infrastructure \u2013\u00a0the API\n   provides as much static type safety as possible and only breaks it\n   where there\u2019s no other option. For example the\n   `Injector.get <https://injector.readthedocs.io/en/latest/api.html#injector.Injector.get>`__\n   method is typed such that ``injector.get(SomeType)`` is statically\n   declared to return an instance of ``SomeType``, therefore making it\n   possible for tools such as `mypy <https://github.com/python/mypy>`__\n   to type-check correctly the code using it.\n\n-  The client code only knows about dependency injection to the extent\n   it needs \u2013\u00a0\n   ```inject`` <https://injector.readthedocs.io/en/latest/api.html#injector.inject>`__,\n   ```Inject`` <https://injector.readthedocs.io/en/latest/api.html#injector.Inject>`__\n   and\n   ```NoInject`` <https://injector.readthedocs.io/en/latest/api.html#injector.NoInject>`__\n   are simple markers that don\u2019t really do anything on their own and\n   your code can run just fine without Injector orchestrating things.\n\nHow to get Injector?\n~~~~~~~~~~~~~~~~~~~~\n\n-  GitHub (code repository, issues):\n   https://github.com/alecthomas/injector\n\n-  PyPI (installable, stable distributions):\n   https://pypi.org/project/injector/. You can install it using pip:\n\n   .. code:: bash\n\n      pip install injector\n\n-  Documentation: https://injector.readthedocs.org\n\n-  Change log: https://injector.readthedocs.io/en/latest/changelog.html\n\nInjector works with CPython 3.7+ and PyPy 3 implementing Python 3.7+.\n\nA Quick Example\n---------------\n\n.. code:: python\n\n   >>> from injector import Injector, inject\n   >>> class Inner:\n   ...     def __init__(self):\n   ...         self.forty_two = 42\n   ...\n   >>> class Outer:\n   ...     @inject\n   ...     def __init__(self, inner: Inner):\n   ...         self.inner = inner\n   ...\n   >>> injector = Injector()\n   >>> outer = injector.get(Outer)\n   >>> outer.inner.forty_two\n   42\n\nOr with ``dataclasses`` if you like:\n\n.. code:: python\n\n   from dataclasses import dataclass\n   from injector import Injector, inject\n   class Inner:\n       def __init__(self):\n           self.forty_two = 42\n\n   @inject\n   @dataclass\n   class Outer:\n       inner: Inner\n\n   injector = Injector()\n   outer = injector.get(Outer)\n   print(outer.inner.forty_two)  # Prints 42\n\nA Full Example\n--------------\n\nHere\u2019s a full example to give you a taste of how Injector works:\n\n.. code:: python\n\n   >>> from injector import Module, provider, Injector, inject, singleton\n\nWe\u2019ll use an in-memory SQLite database for our example:\n\n.. code:: python\n\n   >>> import sqlite3\n\nAnd make up an imaginary ``RequestHandler`` class that uses the SQLite\nconnection:\n\n.. code:: python\n\n   >>> class RequestHandler:\n   ...   @inject\n   ...   def __init__(self, db: sqlite3.Connection):\n   ...     self._db = db\n   ...\n   ...   def get(self):\n   ...     cursor = self._db.cursor()\n   ...     cursor.execute('SELECT key, value FROM data ORDER by key')\n   ...     return cursor.fetchall()\n\nNext, for the sake of the example, we\u2019ll create a configuration type:\n\n.. code:: python\n\n   >>> class Configuration:\n   ...     def __init__(self, connection_string):\n   ...         self.connection_string = connection_string\n\nNext, we bind the configuration to the injector, using a module:\n\n.. code:: python\n\n   >>> def configure_for_testing(binder):\n   ...     configuration = Configuration(':memory:')\n   ...     binder.bind(Configuration, to=configuration, scope=singleton)\n\nNext we create a module that initialises the DB. It depends on the\nconfiguration provided by the above module to create a new DB\nconnection, then populates it with some dummy data, and provides a\n``Connection`` object:\n\n.. code:: python\n\n   >>> class DatabaseModule(Module):\n   ...   @singleton\n   ...   @provider\n   ...   def provide_sqlite_connection(self, configuration: Configuration) -> sqlite3.Connection:\n   ...     conn = sqlite3.connect(configuration.connection_string)\n   ...     cursor = conn.cursor()\n   ...     cursor.execute('CREATE TABLE IF NOT EXISTS data (key PRIMARY KEY, value)')\n   ...     cursor.execute('INSERT OR REPLACE INTO data VALUES (\"hello\", \"world\")')\n   ...     return conn\n\n(Note how we have decoupled configuration from our database\ninitialisation code.)\n\nFinally, we initialise an ``Injector`` and use it to instantiate a\n``RequestHandler`` instance. This first transitively constructs a\n``sqlite3.Connection`` object, and the Configuration dictionary that it\nin turn requires, then instantiates our ``RequestHandler``:\n\n.. code:: python\n\n   >>> injector = Injector([configure_for_testing, DatabaseModule()])\n   >>> handler = injector.get(RequestHandler)\n   >>> tuple(map(str, handler.get()[0]))  # py3/py2 compatibility hack\n   ('hello', 'world')\n\nWe can also verify that our ``Configuration`` and ``SQLite`` connections\nare indeed singletons within the Injector:\n\n.. code:: python\n\n   >>> injector.get(Configuration) is injector.get(Configuration)\n   True\n   >>> injector.get(sqlite3.Connection) is injector.get(sqlite3.Connection)\n   True\n\nYou\u2019re probably thinking something like: \u201cthis is a large amount of work\njust to give me a database connection\u201d, and you are correct; dependency\ninjection is typically not that useful for smaller projects. It comes\ninto its own on large projects where the up-front effort pays for itself\nin two ways:\n\n1. Forces decoupling. In our example, this is illustrated by decoupling\n   our configuration and database configuration.\n2. After a type is configured, it can be injected anywhere with no\n   additional effort. Simply ``@inject`` and it appears. We don\u2019t really\n   illustrate that here, but you can imagine adding an arbitrary number\n   of ``RequestHandler`` subclasses, all of which will automatically\n   have a DB connection provided.\n\nFootnote\n--------\n\nThis framework is similar to snake-guice, but aims for simplification.\n\n\u00a9 Copyright 2010-2013 to Alec Thomas, under the BSD license\n\n.. |image| image:: https://github.com/alecthomas/injector/workflows/CI/badge.svg\n   :target: https://github.com/alecthomas/injector/actions?query=workflow%3ACI+branch%3Amaster\n.. |Coverage Status| image:: https://codecov.io/gh/alecthomas/injector/branch/master/graph/badge.svg\n   :target: https://codecov.io/gh/alecthomas/injector\n\n\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "Injector - Python dependency injection framework, inspired by Guice",
    "version": "0.21.0",
    "project_urls": {
        "Download": "https://pypi.org/project/injector/",
        "Homepage": "https://github.com/alecthomas/injector"
    },
    "split_keywords": [
        "dependency injection",
        "di",
        "dependency injection framework",
        "inversion of control",
        "ioc",
        "inversion of control container"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3018e0a2882bb4bc3f014271e4fcc6c67c39d24ef862de2b460983122594af56",
                "md5": "6e8a4f7d785725789d385fc75904e39c",
                "sha256": "3942c5e4c501d390d5ad1b8d7d486ef93b844934afeeb17211acb6c4ca29eeb4"
            },
            "downloads": -1,
            "filename": "injector-0.21.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6e8a4f7d785725789d385fc75904e39c",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 20322,
            "upload_time": "2023-07-27T00:42:23",
            "upload_time_iso_8601": "2023-07-27T00:42:23.678205Z",
            "url": "https://files.pythonhosted.org/packages/30/18/e0a2882bb4bc3f014271e4fcc6c67c39d24ef862de2b460983122594af56/injector-0.21.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "da91b6da45ee1251c136bda46c2e404e5a056fd47c9cda9d8857974eac9e2f4d",
                "md5": "29f1ddaabf30fab127665633a51603ef",
                "sha256": "919eb6b9f96f40bf98fda34c79762b217bd1544d9adc35805ff2948e92356c9c"
            },
            "downloads": -1,
            "filename": "injector-0.21.0.tar.gz",
            "has_sig": false,
            "md5_digest": "29f1ddaabf30fab127665633a51603ef",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 52406,
            "upload_time": "2023-07-27T00:42:25",
            "upload_time_iso_8601": "2023-07-27T00:42:25.424067Z",
            "url": "https://files.pythonhosted.org/packages/da/91/b6da45ee1251c136bda46c2e404e5a056fd47c9cda9d8857974eac9e2f4d/injector-0.21.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-27 00:42:25",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "alecthomas",
    "github_project": "injector",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "injector"
}
        
Elapsed time: 0.09398s