A Container for the Dependency Injection in Python.

Overview

Python Dependency Injection library

aiodi is a Container for the Dependency Injection in Python.

Installation

Use the package manager pip to install aiodi.

pip install aiodi

Documentation

Usage

from abc import ABC, abstractmethod
from logging import Logger, getLogger, NOTSET, StreamHandler, Formatter
from os import getenv

from aiodi import Container
from typing import Optional, Union

_CONTAINER: Optional[Container] = None


def get_simple_logger(
        name: Optional[str] = None,
        level: Union[str, int] = NOTSET,
        fmt: str = '[%(asctime)s] - %(name)s - %(levelname)s - %(message)s',
) -> Logger:
    logger = getLogger(name)
    logger.setLevel(level)
    handler = StreamHandler()
    handler.setLevel(level)
    formatter = Formatter(fmt)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


class GreetTo(ABC):
    @abstractmethod
    def __call__(self, who: str) -> None:
        pass


class GreetToWithPrint(GreetTo):
    def __call__(self, who: str) -> None:
        print('Hello ' + who)


class GreetToWithLogger(GreetTo):
    _logger: Logger

    def __init__(self, logger: Logger) -> None:
        self._logger = logger

    def __call__(self, who: str) -> None:
        self._logger.info('Hello ' + who)


def container() -> Container:
    global _CONTAINER
    if _CONTAINER:
        return _CONTAINER
    di = Container({'env': {
        'name': getenv('APP_NAME', 'aiodi'),
        'log_level': getenv('APP_LEVEL', 'INFO'),
    }})
    di.resolve([
        (
            Logger,
            get_simple_logger,
            {
                'name': di.resolve_parameter(lambda di_: di_.get('env.name', typ=str)),
                'level': di.resolve_parameter(lambda di_: di_.get('env.log_level', typ=str)),
            },
        ),
        (GreetTo, GreetToWithLogger),  # -> (GreetTo, GreetToWithLogger, {})
        GreetToWithPrint,  # -> (GreetToWithPrint, GreetToWithPrint, {})
    ])
    di.set('who', 'World!')
    # ...
    _CONTAINER = di
    return di


def main() -> None:
    di = container()

    di.get(Logger).info('Just simple call get with the type')

    for greet_to in di.get(GreetTo, instance_of=True):
        greet_to(di.get('who'))


if __name__ == '__main__':
    main()

Requirements

  • Python >= 3.6

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

Comments
  • Add status badges to README.md

    Add status badges to README.md

    As other Open source projects have, add the badges of the status of the CI passing the tests in GitHub Actions, of the latest version available in PyPi and the number of total downloads to the README.md.

    documentation good first issue 
    opened by ticdenis 0
  • Supports multiple casting for variables using ContainerBuilder

    Supports multiple casting for variables using ContainerBuilder

    Currently we have 3 options to cast variables using the ContainerBuilder:

    # pyproject.toml
    
    [tool.aiodi.variables]
    # Get static text.
    debug = "Text"
    # Get as str a variable.
    debug2 = "%var(debug)%"
    # Cast to int an environment variable.
    debug3 = "%env(int:APP_DEBUG, '1')%"
    

    But we can not do:

    # pyproject.toml
    
    [tool.aiodi.variables]
    # ...
    debug4 = "%env(bool:int:APP_DEBUG, '1')%"
    

    We've detected that this is a common operation so would be great have it integrate it on ContainerBuilder.

    enhancement 
    opened by ticdenis 0
  • Support for resolving Generic types as argument

    Support for resolving Generic types as argument

    Currently is not supported if we have something like:

    from typing import TypeVar
    
    
    Driver = TypeVar('Driver')
    
    class Connection(Generic[Driver]):
      ...
      
    class FakeConnection(Connection[int]):
      ...
      
    class App:
      def __init__(self, connection: Connection[int]) -> None:
        self._connection = connection
    

    When we try to resolve Connection as an argument will fail, example:

    # ...
    
    di.resolve([
      (Connection, FakeConnection()),
      (App), # will fail
    ])
    
    bug help wanted 
    opened by ticdenis 0
  • Improve CommandBuilder dependency resolution system

    Improve CommandBuilder dependency resolution system

    It is currently quite convoluted, abusing loops with a limit of the cube depending on the number of elements to be solved and messing up the unsolved elements so that they can be incorporated into the head of the next iteration and avoid infinite loops. But there can be.

    The dependency resolution system should be improved, as an idea based on a tree system.

    bug enhancement help wanted 
    opened by ticdenis 0
  • Support for resolving typed lists with ContainerBuilder

    Support for resolving typed lists with ContainerBuilder

    This is currently not possible and it would be great if examples like the following could work.

    class UserPermission:
      pass
    
    def default_user_permissions() -> list[UserPermission]:
      return [UserPermission()]
    
    class UserHandler:
      __slots__  = '_permissions'
      
      def __init__(self, permissions: list[UserPermission]) -> None:
        self._permissions = permissions 
    
    [tool.aiodi.services."default_user_permissions"]
    class = "sample.default_user_permissions"
    
    [tool.aiodi.services."UserHandler"]
    class = "sample.UserHandler" # <- this will fails because library does not inspect list type.
    
    enhancement help wanted 
    opened by ticdenis 0
Releases(1.1.4)
  • 1.1.4(Jun 9, 2022)

  • 1.1.2(Feb 20, 2022)

    What's Changed

    • refactor(*): Improve ContainerBuilder architecture by @ticdenis in https://github.com/ticdenis/python-aiodi/pull/6
    • Support multiple casting for variables and allows "None" as None for default values by @ticdenis in https://github.com/ticdenis/python-aiodi/pull/7

    Full Changelog: https://github.com/ticdenis/python-aiodi/compare/1.1.1...1.1.2

    Source code(tar.gz)
    Source code(zip)
  • 1.1.1(Feb 10, 2022)

  • 1.1.0(Jan 19, 2022)

    What's Changed

    • release(1.0.0): Initial release by @ticdenis in https://github.com/ticdenis/python-aiodi/pull/2
    • docs: Add symbolic link for index.md to en/index.md by @ticdenis in https://github.com/ticdenis/python-aiodi/pull/3
    • feat(*): Add support for pyproject.toml by @ticdenis in https://github.com/ticdenis/python-aiodi/pull/4

    Full Changelog: https://github.com/ticdenis/python-aiodi/commits/1.1.0

    Source code(tar.gz)
    Source code(zip)
Owner
Denis NA
Denis NA
Pass arguments by reference—in Python!

byref Pass arguments by reference—in Python! byrefis a decorator that allows Python functions to declare reference parameters, with similar semantics

9 Feb 10, 2022
A script copies movie and TV files to your GD drive, or create Hard Link in a seperate dir, in Emby-happy struct.

torcp A script copies movie and TV files to your GD drive, or create Hard Link in a seperate dir, in Emby-happy struct. Usage: python3 torcp.py -h Exa

ccf2012 105 Dec 22, 2022
Python implementation of Gorilla time series compression

Gorilla Time Series Compression This is an implementation (with some adaptations) of the compression algorithm described in section 4.1 (Time series c

Ghiles Meddour 19 Jan 01, 2023
Homebase Name Changer for Fortnite: Save the World.

Homebase Name Changer This program allows you to change the Homebase name in Fortnite: Save the World. How to use it? After starting the HomebaseNameC

PRO100KatYT 7 May 21, 2022
This is discord nitro code generator and checker made with python. This will generate nitro codes and checks if the code is valid or not. If code is valid then it will print the code leaving 2 lines and if not then it will print '*'.

Discord Nitro Generator And Checker ⚙️ Rᴜɴ Oɴ Rᴇᴘʟɪᴛ 🛠️ Lᴀɴɢᴜᴀɢᴇs Aɴᴅ Tᴏᴏʟs If you are taking code from this repository without a fork, then atleast

Vɪɴᴀʏᴀᴋ Pᴀɴᴅᴇʏ 37 Jan 07, 2023
jfc is an utility to make reviewing ArXiv papers for your Journal Club easier.

jfc is an utility to make reviewing ArXiv papers for your Journal Club easier.

Miguel M. 3 Dec 20, 2021
A Python utility belt containing simple tools, a stdlib like feel, and extra batteries. Hashing, Caching, Timing, Progress, and more made easy!

Ubelt is a small library of robust, tested, documented, and simple functions that extend the Python standard library. It has a flat API that all behav

Jon Crall 638 Dec 13, 2022
Similar looking domain detection using python fuzzywuzzy

Major cause of phishing and BEC incident is similar looking domain, if you detect it early, you can prevent incidents early, python fuzzywuzzy module let you do that

2 Nov 07, 2021
ColorController is a Pythonic interface for managing colors by english-language name and various color values.

ColorController.py Table of Contents Encode color data in various formats. 1.1: Create a ColorController object using a familiar, english-language col

Tal Zaken 2 Feb 12, 2022
Utility to add/remove licenses to/from source files

Utility to add/remove licenses to/from source files. Supports processing any combination of globs, files, and directories (recurse). Pruning options allow skipping non-licensing files.

Eduardo Ponce Mojica 2 Jan 29, 2022
Casefy (/keɪsfaɪ/) is a lightweight Python package to convert the casing of strings

Casefy (/keɪsfaɪ/) is a lightweight Python package to convert the casing of strings. It has no third-party dependencies and supports Unicode.

Diego Miguel Lozano 12 Jan 08, 2023
NetConfParser is a tool that helps you analyze the rpcs coming and going from a netconf client to a server

NetConfParser is a tool that helps you analyze the rpcs coming and going from a netconf client to a server

Aero 1 Mar 31, 2022
A simple and easy to use Spam Bot made in Python!

This is a simple spam bot made in python. You can use to to spam anyone with anything on any platform.

7 Sep 08, 2022
Dynamic key remapper for Wayland Window System, especially for Sway

wayremap Dynamic keyboard remapper for Wayland. It works on both X Window Manager and Wayland, but focused on Wayland as it intercepts evdev input and

Kay Gosho 50 Nov 29, 2022
A python module to manipulate XCode projects

This module can read, modify, and write a .pbxproj file from an Xcode 4+ projects. The file is usually called project.pbxproj and can be found inside the .xcodeproj bundle. Because some task cannot b

Ignacio Calderon 1.1k Jan 02, 2023
Color box that provides various colors‘ rgb decimal code.

colorbox Color box that provides various colors‘ rgb decimal code

1 Dec 07, 2021
python package for generating typescript grpc-web stubs from protobuf files.

grpc-web-proto-compile NOTE: This package has been superseded by romnn/proto-compile, which provides the same functionality but offers a lot more flex

Roman Dahm 0 Sep 05, 2021
Skywater 130nm Klayout Device Generators PDK

Skywaters 130nm Technology for KLayout Device Generators Mabrains is excited to share with you our Device Generator Library for Skywater 130nm PDK. It

Mabrains 18 Dec 14, 2022
a tool for annotating table

table_annotate_tool a tool for annotating table motivated by wiki2bio,we create a tool to annoate all types of tables,this tool can annotate a table w

wisdom under lemon trees 4 Sep 23, 2021
A (very dirty) experiment to remove layers from a Docker image.

Surgically remove layers from a Docker image (with a chainsaw)

Jérôme Petazzoni 9 Jun 08, 2022