DI Implementation

Lightweight contextvar-based dependency injection-adjacent solution.

Functions

disnake_compass.internal.di.register_dependencies(*dependencies)[source]

Register any number of dependencies.

This returns a mapping of contextvars.Tokens that should be passed to reset_dependencies() for cleanup.

While dependencies are registered, resolve_dependency() can be used to get it for the current async context.

Parameters:

*dependencies (object) – Objects to register as dependencies. Their type must be hashable. (This should automatically hold for most classes.)

Returns:

A mapping of the types of the registered dependencies to contextvar tokens used to reset their respective contextvars. This is meant to be passed to reset_dependencies() for cleanup.

Return type:

Dict[Type[Any], contextvars.Token[object]]

disnake_compass.internal.di.reset_dependencies(tokens)[source]

Reset dependencies that are no longer in use.

This is meant to be used in conjunction with register_dependencies().

Parameters:

tokens (Mapping[type[Any], Token[object]]) – A mapping of the types of the registered dependencies to contextvar tokens used to reset their respective contextvars. This mapping is created and returned by register_dependencies().

disnake_compass.internal.di.resolve_dependency(dependency_type, default=OmittedType.Omitted)[source]

Resolve a dependency given a type and an optional default.

If a dependency was set using register_dependency() in the current context, this function returns it. If it is not found, the default is returned instead. If no default was provided, a LookupError is raised instead.

Parameters:
  • dependency_type (type[_T]) – The type to resolve to an object.

  • default (OmittedType | _T) – The default to use if resolving did not return an object.

Returns:

The resolved dependency or the default.

Return type:

object

Raises:

LookupError – The dependency type could not be resolved and no default was provided.