Skip to content

Commit

Permalink
Removed dynamic container and its documentation. Added safeguards. (#152
Browse files Browse the repository at this point in the history
)
  • Loading branch information
alexanderlazarev0 authored Feb 2, 2025
1 parent 1cb1087 commit 884653f
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 38 deletions.
1 change: 0 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
introduction/inject-factories
introduction/scopes
introduction/multiple-containers
introduction/dynamic-container
introduction/application-settings
.. toctree::
Expand Down
25 changes: 0 additions & 25 deletions docs/introduction/dynamic-container.md

This file was deleted.

20 changes: 8 additions & 12 deletions tests/test_dynamic_container.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import datetime

import pytest

from tests import container
from that_depends import BaseContainer, providers


class DIContainer(BaseContainer):
sync_resource: providers.Resource[datetime.datetime]
async_resource: providers.Resource[datetime.datetime]


DIContainer.sync_resource = providers.Resource(container.create_sync_resource)
DIContainer.async_resource = providers.Resource(container.create_async_resource)


async def test_dynamic_container() -> None:
sync_resource = await DIContainer.sync_resource()
async_resource = await DIContainer.async_resource()

assert isinstance(sync_resource, datetime.datetime)
assert isinstance(async_resource, datetime.datetime)
async def test_dynamic_container_not_supported() -> None:
new_provider = providers.Resource(container.create_sync_resource)
with pytest.raises(AttributeError):
DIContainer.sync_resource = new_provider

await DIContainer.tear_down()
with pytest.raises(AttributeError):
DIContainer.something_new = new_provider
16 changes: 16 additions & 0 deletions that_depends/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ class BaseContainerMeta(abc.ABCMeta):

_instances: typing.ClassVar[list[type["BaseContainer"]]] = []

_MUTABLE_ATTRS = (
"__abstractmethods__",
"__parameters__",
"_abc_impl",
"providers",
"containers",
)

_lock: Lock = Lock()

@classmethod
Expand All @@ -56,3 +64,11 @@ def __new__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, typing
def get_instances(cls) -> list[type["BaseContainer"]]:
"""Get all instances that inherit from BaseContainer."""
return cls._instances

@override
def __setattr__(cls, key: str, value: typing.Any) -> None:
if key in cls._MUTABLE_ATTRS: # Allow modification of mutable attributes
super().__setattr__(key, value)
else:
msg = f"Cannot add new attribute '{key}' to class '{cls.__name__}'"
raise AttributeError(msg)

0 comments on commit 884653f

Please sign in to comment.