Skip to main content

Unintrusive dependency injection for Python 3.6 +

Project description

Punq

https://travis-ci.org/bobthemighty/punq.svg?branch=master https://img.shields.io/codecov/c/github/bobthemighty/punq.svg?style=flat Documentation Status

An unintrusive library for dependency injection in modern Python. Inspired by Funq, Punq is a dependency injection library you can understand.

  • No global state

  • No decorators

  • No weird syntax applied to arguments

  • Small and simple code base with 100% test coverage and developer-friendly comments.

Installation

Punq is available on the cheese shop.

pip install punq

Documentation is available on Read the docs.

Quick Start

Punq avoids global state, so you must explicitly create a container in the entrypoint of your application:

import punq

container = punq.Container()

Once you have a container, you can register your application’s dependencies. In the simplest case, we can register any arbitrary object with some key:

container.register("connection_string", "postgresql://...")

We can then request that object back from the container:

conn_str = container.resolve("connection_string")

Usually, though, we want to register some object that implements a useful service.:

class ConfigReader:
   def get_config(self):
      pass

class EnvironmentConfigReader(ConfigReader):
   def get_config(self):
      return {
         "logging": {
            "level": os.env.get("LOGGING_LEVEL", "debug")
         }
         "greeting": os.env.get("GREETING", "Hello world")
      }

container.register(ConfigReader, EnvironmentConfigReader)

Now we can resolve the ConfigReader service, and receive a concrete implementation:

config = container.resolve(ConfigReader).get_config()

If our application’s dependencies have their own dependencies, Punq will inject those, too:

class Greeter:
   def greet(self):
      pass


class ConsoleGreeter:
   def __init__(self, config_reader: ConfigReader):
      self.config = config_reader.get_config()

   def greet(self):
      print(self.config['greeting'])


container.register(Greeter)
container.resolve(Greeter).greet()

If you just want to resolve an object without having any base class, that’s okay:

class Greeter:
   def __init__(self, config_reader: ConfigReader):
      self.config = config_reader.get_config()

   def greet(self):
      print(self.config['greeting'])

container.register(Greeter)
container.resolve(Greeter).greet()

And if you need to have a singleton object for some reason, we can tell punq to register a specific instance of an object:

class FileWritingGreeter:
   def __init__(self, path, greeting):
      self.path = path
      self.message = greeting
      self.file = open(self.path, 'w')

   def greet(self):
      self.file.write(self.message)


one_true_greeter = FileWritingGreeter("/tmp/greetings", "Hello world")
container.register(Greeter, instance=one_true_greeter)

You might not know all of your arguments at registration time, but you can provide them later:

container.register(Greeter, FileWritingGreeter)
greeter = container.resolve(Greeter, path="/tmp/foo", greeting="Hello world")

Conversely, you might want to provide arguments at registration time, without adding them to the container:

container.register(Greeter, FileWritingGreeter, path="/tmp/foo", greeting="Hello world")

Fuller documentation is available on Read the docs.

Changelog

0.2.1 2019-05-22

Fixes

Punq will now prefer to use a provided resolution argument instead of creating it anew.

0.2.0 2019-02-12

Fixes

Added handling for typing.ForwardRef

Breaking Changes

Added explicit instance kwarg to register which replaces the previous behaviour where container.register(Service, someInstance) would register a concrete instance. This fixes https://github.com/bobthemighty/punq/issues/6

0.1.2-alpha 2019-02-11

Feature

First automatic Travis deploy

0.0.1

Basic resolution and registration works Punq is almost certainly slow as a dog, non thread-safe, and prone to weird behaviour in the edge cases.

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

punq-0.3.0.tar.gz (24.0 kB view details)

Uploaded Source

File details

Details for the file punq-0.3.0.tar.gz.

File metadata

  • Download URL: punq-0.3.0.tar.gz
  • Upload date:
  • Size: 24.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.1

File hashes

Hashes for punq-0.3.0.tar.gz
Algorithm Hash digest
SHA256 69b80d957eb28d7d2d89459fd16561063592f20e8bc00259dce39c29b60cfbd0
MD5 80d0df400911531c10c920036149c38d
BLAKE2b-256 eb4378c5a5d9cf67a42bde18f2a6e05c29d647a15b49ffb6097524af161d0359

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