Skip to main content

Lightweight dependency injection for pure OOP.

Project description

Philosophy

Injecting class dependencies comes in 3 distinct ways :

  • using class attributes (okay)

  • using setters (better)

  • using constructor (best)

Wyre allows you to declare the dependencies of a given class using kwargs on a constructor. A single decorator @inject does the trick. This is particularly handy when your dependency tree grows large and deep. For example, this dependency chain : A < B < C < D < E, would require you to write a = A(B(C(D(E())))) in order to create an instance of your class.

Using Wyre, you keep :

  • your production code clean by writing just A() since it works recursively

  • your unit tests simple : A(b=Mock()) is all you need to mock out dependencies

Usage

class C:
    name = 'Bob'


class B:
    @inject
    def __init__(self, other_dependency=C):
        self.c = other_dependency

    def say_hello(self):
        return 'Hello %s !' % self.c.name


class A:
    @inject
    def __init__(self, dependency=B):
        self.b = dependency

    def greetings(self):
        return self.b.say_hello()

a = A()
a.greetings() # returns 'Hello Bob !'

Since __init__ is decorated with @inject, B instance will be created and injected in A at instantiation time.

Limitations

Important notes on what @inject does :

  • If an instance of a dependency is provided in kwargs, it will be preserved and not overridden by a new instance.

  • Circular dependencies are detected at instantiation time : an InjectionError will be raised.

  • You can only use it on __init__(). If you decorate any other function : an InjectionError will be raised.

  • If no dependency is found among declared kwargs : an InjectionError will be raised.

  • Wyre is strongly opinionated about dependency injection. As a matter of fact, singletons are not even considered.

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

wyre-0.2.1.tar.gz (5.0 kB view details)

Uploaded Source

File details

Details for the file wyre-0.2.1.tar.gz.

File metadata

  • Download URL: wyre-0.2.1.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for wyre-0.2.1.tar.gz
Algorithm Hash digest
SHA256 154f9ea45193729a020f0a2c03ef922fb912345073dc30e6a40ee5a540f05eea
MD5 fb8aa3ba07c4d14f8cfe12727230c71b
BLAKE2b-256 3a1aafcc4e737f363360f36cab9d73d7ede809e7261dd658de6facd05181b562

See more details on using hashes here.

Supported by

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