Python injection framework

Is there a framework equivalent to Guice ( http://code.google.com/p/google-guice ) for Python?

+43
python dependency-injection
Oct 01 '08 at 4:25
source share
14 answers

I have not used it, but Spring Python is based on Spring and implements Inversion of Control .

There is also a Guice in Python project: snake-guice

+13
01 Oct '08 at 7:20
source share

Spring Python is a branch of the Java Spring Framework and Spring Security designed for Python. This project currently contains the following features:

  • Inversion Of Control - Use either classic XML or the python @Object decorator (similar to Spring's JavaConfig subproject) to bind things together. Although the @Object format is not identical to the Guice style (centralized wiring and wiring information in each class), this is a valuable way to connect your python application.
  • Aspect-oriented programming — Interceptors are used in the horizontal programming paradigm (instead of vertical OOP inheritance) for things like transactions, security, and caching.
  • DatabaseTemplate. Reading from the database requires a monotonous cycle of opening cursors, reading rows and closing cursors, along with exception handlers. With this class of templates, all you need is an SQL query and a string processing function. Spring Python does the rest.
  • Database transactions. Combining multiple calls into a database with transactions can make code difficult to read. This module provides several ways to define transactions without complicating the work.
  • Security - plug-in security interceptors to block access to your methods, using both authentication and domain authorization.
  • Remoting - easily convert a local application to a distributed one. If you have already created client and server fragments using the IoC container, switching from local to distributed is just a configuration change.
  • Samples - To demonstrate the various Spring Python features, some sample applications were created:
    • PetClinic - Spring A sample web application for the Framework template was rebuilt from scratch using python web containers, including: CherryPy . Go to check it out how to use this infrastructure. (NOTE: Other python web frames will be added to this list in the future).
    • Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple demo!
    • Spring Bot - Use Spring Python to create a tiny bot to control the IRC channel of your open source project.
+25
Oct 15 '08 at 12:16
source share

I like this simple and neat structure.

http://pypi.python.org/pypi/injector/

Dependency injection as a formal template is less useful in Python than in other languages, primarily due to the support of keyword arguments, the ease with which objects can be mocked, and its dynamic nature.

However, a framework to assist in this process can significantly reduce boiler plates from larger applications. That the injector can help. It automatically and transitively provides keyword arguments with their meanings. As an added benefit, Injector encourages beautifully separated code with the s module.

Being inspired by Gis, he does not slavishly replicate his APIs. Providing the Pythonic API excels fidelity.

+13
Oct 19 '12 at 9:59
source share

As an alternative to monkeypatching, I like DI. A mortgaged project, such as http://code.google.com/p/snake-guice/ , may match the invoice.

Or see the blog post Injecting Dependencies in Python by Dennis Kempin (August '08).

+9
Nov 08 '08 at 20:50
source share
+6
01 Oct. '08 at 7:58
source share

pinject ( https://github.com/google/pinject ) is a newer alternative. It seems to be supported by Google and follows a similar pattern for Guice ( https://code.google.com/p/google-guice/ ), it is a Java counterpart.

+6
Sep 09 '13 at 16:36
source share

There are several Guicey python-inject projects . It's quite active, and LOT has less code than Spring -python, but again, I haven't found a reason to use it yet.

+3
Apr 20 '10 at 2:59 a.m.
source share

If you just want to do dependency injection in Python, you don't need a framework. See Injection Dependency Python Path . It is very fast and simple, and only c. 50 lines of code.

+2
Apr 03 '10 at 17:11
source share

Here is a small example of a dependency injection container that injects a constructor based on the names of the constructor arguments:

http://code.activestate.com/recipes/576609-non-invasive-dependency-injection/

+1
May 4 '11 at 2:18
source share

Leave my 5 cents here :)

https://pypi.python.org/pypi/dependency_injector

"""Pythonic way for Dependency Injection.""" from dependency_injector import providers from dependency_injector import injections @providers.DelegatedCallable def get_user_info(user_id): """Return user info.""" raise NotImplementedError() @providers.Factory @injections.inject(get_user_info=get_user_info) class AuthComponent(object): """Some authentication component.""" def __init__(self, get_user_info): """Initializer.""" self.get_user_info = get_user_info def authenticate_user(self, token): """Authenticate user by token.""" user_info = self.get_user_info(user_id=token + '1') return user_info print AuthComponent print get_user_info @providers.override(get_user_info) @providers.DelegatedCallable def get_user_info(user_id): """Return user info.""" return {'user_id': user_id} print AuthComponent().authenticate_user(token='abc') # {'user_id': 'abc1'} 

UPDATED

Some time has passed, and the dependency injector is now slightly different. Better start with the Dependency Injector GitHub page for actual examples - https://github.com/ets-labs/python-dependency-injector

+1
Mar 06 '16 at 20:05
source share

I made a lib for this https://github.com/ettoreleandrotognoli/python-cdi Hope this helps

It is available on pypi: https://pypi.python.org/pypi/pycdi

With it, you can do injections with python2

 import logging from logging import Logger from pycdi import Inject, Singleton, Producer from pycdi.shortcuts import call @Producer(str, _context='app_name') def get_app_name(): return 'PyCDI' @Singleton(produce_type=Logger) @Inject(app_name=str, _context='app_name') def get_logger(app_name): return logging.getLogger(app_name) @Inject(name=(str, 'app_name'), logger=Logger) def main(name, logger): logger.info('I\'m starting...') print('Hello World!!!\nI\'ma example of %s' % name) logger.debug('I\'m finishing...') call(main) 

And using type hints from python3

 import logging from logging import Logger from pycdi import Inject, Singleton, Producer from pycdi.shortcuts import call @Producer(_context='app_name') def get_app_name() -> str: return 'PyCDI' @Singleton() @Inject(logger_name='app_name') def get_logger(logger_name: str) -> Logger: return logging.getLogger(logger_name) @Inject(name='app_name') def main(name: str, logger: Logger): logger.info('I\'m starting...') print('Hello World!!!\nI\'ma example of %s' % name) logger.debug('I\'m finishing...') call(main) 
+1
Nov 06 '17 at 11:37
source share

If you prefer a really tiny solution, there is a little feature there, it's just a dependency setting tool.

https://github.com/liuggio/Ultra-Lightweight-Dependency-Injector-Python

0
Apr 09 2018-11-11T00:
source share

Here's dyject ( http://dyject.com ), a lightweight structure for both Python 2 and Python 3 that uses the built-in ConfigParser

0
Apr 29 '13 at 5:59 on
source share

If you need a look like this (new new, as they say), I recently did something close in Python 3 that best suited my simple needs for a side project.

All you need is @inject by method (including, of course, __init__). The rest is done through annotations.

 from py3njection import inject from some_package import ClassToInject class Demo: @inject def __init__(self, object_to_use: ClassToInject): self.dependency = object_to_use demo = Demo() 

https://pypi.python.org/pypi/py3njection

0
Dec 17 '15 at 23:35
source share



All Articles