AdditionalConfig

This class allows you to add additional names to the Di container.

  1. Overview

Overview

The idea here is that you extend the AdditonalConfig class and attach as many provide_* methods to the class as you want. This allows the developer to declare a number of dependencies and easily attach them to the Di container in one go - helpful for modules that come with a variety of things that they want to make available to developers.

When an AdditionalConfig instance is attached to the Di container, the container (in essence) finds all the provide_* methods in the class and registers the corresponding name in the Di container - e.g. if you have a method called provide_widget then when a class or function requests an argument named widget from the Di container, the container will call the provide_widget method on your instance and pass along the return value to the thing that requested a widget. The provide_* methods can declare their own dependencies, including ones declared in the same AdditionalConfig class (they just can’t be circular, of course).

As always, keep in mind the priority of dependency injection names (see the clearskies.di.Di class for full details). If two AdditionalConfig objects declare a provide_* method with the same name, then the Di system will call the method for the AdditionalConfig object that was added last.

By default the Di system caches all values. If you have a dependency that shouldn’t be cached, you can extend the can_cache method and have it return True/False depending on the name and context.

Example:

from clearskies.di import Di, AdditionalConfig


class MyAdditionalConfig(AdditionalConfig):
    def provide_inner_dependency(self):
        return 5

    def provide_important_thing(self, inner_dependency):
        return inner_dependency * 10


class AnotherAdditionalConfig(AdditionalConfig):
    def provide_inner_dependency(self):
        return 10


di = Di(additional_configs=[MyAdditionalConfig(), AnotherAdditionalConfig()])
# Equivalent:
# di = Di()
# di.add_addtional_configs([MyAdditionalConfig(), AnotherAdditionalConfig()])


def my_function(important_thing):
    print(important_thing)  # prints 100