Skip to main content

Simple ioc framework for python

Project description

Simple Python IoC Framework

Usage

Examples how to use this library.

Singleton with no dependency's

Registering a singleton means we will return the same instance for every ioc.get request.

class MyInterface(ABC):
    @abstractmethod
    def do_it(self):
        ...

class MyClass(MyInterface):

    def __init__(self, name):
        self.name = name

    def do_it(self):
        print(f"{self.name} I did it")

ioc = IOCContainer()
ioc.register_singleton(MyInterface, MyClass("John Doe"))
ioc.get(MyInterface).do_it()

Singleton with dependency's

Creating a singleton with dependency enables us to reuse already registered configurations.

⚠️ A singleton should only have singletons as dependency's if we use a transient, the transient will become a singleton.

class AppConfig(BaseModel):
    user_name: str

ioc = IOCContainer()
ioc.register_singleton(AppConfig, AppConfig(user_name="John Doe"))
ioc.register_singleton(MyInterface, lambda x: MyClass(
    name=x.get(AppConfig).user_name)
    )
ioc.get(MyInterface).do_it()

Transient

Registering a transient means we will generate the instance for every ioc.get request.

class LoveCalculator():
    def __init__(self, name: str):
        self.name = name
        self.in_love_percent = random.randint(0, 100)

    def print(self):
        print(f"[{self.name}] -> {self.in_love_percent}%")

ioc = IOCContainer()
ioc.register_singleton(AppConfig, AppConfig(user_name="John Doe"))
ioc.register_transient(LoveCalculator, lambda x: LoveCalculator(
    name=x.get(AppConfig).username)
    )

ioc.get(LoveCalculator).print()
# output: John Doe -> 20%

ioc.get(LoveCalculator).print()
# output: John Doe -> 53%

Scoped

Register a scoped resource this can be used to get the same instance every time as long as you are in the scope. Another usage could be session aware stuff like opening and closing a db session within that scope.

class Database():
    def __init__(self, connection_string: str):
        self._cs = connection_string
        self._session_factory = SessionFactory()

    def get_session(self) -> Generator[Session, None, None]
        session = self._session_factory()
        try:
            yield session
        except:
            session.rollback()
        finally:
            session.close()


ioc = IOCContainer()
ioc.register_singleton(AppConfig, AppConfig(connection_string="Secret123"))
ioc.register_singleton(Database, lambda x: Database(
    connection_string=x.get(AppConfig).connection_string
    )
)
ioc.register_scoped(Session, lambda: x.get(Database).get_session)
ioc.register_transient(LoveCalculator, lambda x: LoveCalculator(
    db_session = x.get(Session)
))

#DB Session gets automatically closed when leaving the scope 
with ioc.create_scope() as scope:
    scope.get(LoveCalculator).print()

Development

Run basic tests

pdm test

Run coverage check

pdm coverage

Build and deploy

pdm build
pdm publish

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

iocpy3-0.1.1.tar.gz (15.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

iocpy3-0.1.1-py3-none-any.whl (12.3 kB view details)

Uploaded Python 3

File details

Details for the file iocpy3-0.1.1.tar.gz.

File metadata

  • Download URL: iocpy3-0.1.1.tar.gz
  • Upload date:
  • Size: 15.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.20.1 CPython/3.8.5 Windows/10

File hashes

Hashes for iocpy3-0.1.1.tar.gz
Algorithm Hash digest
SHA256 3c80e547d30a28e6ab3d84c21de6ea992e11684e01c1c7684557b20aefdde846
MD5 59097e99f32eaf236f862464dfc9ffed
BLAKE2b-256 d536aa4454f76fee1aff0987f9a54ecf4adb0ef0eb3006d26f0c04c855fb4289

See more details on using hashes here.

File details

Details for the file iocpy3-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: iocpy3-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 12.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.20.1 CPython/3.8.5 Windows/10

File hashes

Hashes for iocpy3-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 91bb8c55fa911f6cb710ff95523236b03d0493fbaee436b63490511b31021156
MD5 021e64524602340b0674c53bba0d2109
BLAKE2b-256 da4b524fe4b6b02001af8eb7b45272244d7ba69fcac0d47ae13e0a77607633b4

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