Fang

2015-08-01

Fang is a dependency injection library for Python.

Originally developed in 2015, Fang adds dependency injection to Python with an idiomatic decorator syntax.

Fang was presented in a talk at the PyCon 2015 conference.

Rationale

Dependency injection (DI) is uncommon in Python. It's usually written off as a tool for other languages – languages with static typing, strict interfaces, etc – which is unneeded in Python.

But, dependency injection can actually give plenty of benefits even for Python programs. Among them:

Dependency injection in other languages is usually quite complex. DI frameworks often use their own configuration language (often written in XML), mandate strict interfaces, use factory classes, and so on. There are a lot of pieces, and few of them fit into Python's existing ecosystem and programming style.

Fang adds dependency injection, but in a Pythonic way, while still maintaining the benefits. Particularly, in Fang:

Examples

Here's a simple (if contrived) example of a short program which multiplies two numbers. One of the numbers is given as a parameter to a function call. The other number is configured via dependency injection:

import fang

di = fang.Di(namespace='.com.example.myproject')

@di.dependsOn('multiplier')
def multiply(n):
    '''Multiply the given number n by some configured multiplier.'''
    multiplier = di.resolver.unpack(multiply)
    return multiplier * n

providers = fang.ResourceProviderRegister(namespace='.com.example.myproject')

@providers.register('multiplier')
def give_multiplier():
    '''Give a multiplier of 2.'''
    return 2

def main():
    # Here at our program entry-point, we configure what set of providers
    # will be used to meet our dependencies
    di.providers.load(providers)
    # Prints 10
    print(multiply(5))

if __name__ == '__main__':
    main()