Skip to content

Commit

Permalink
✨ feat: add state func
Browse files Browse the repository at this point in the history
  • Loading branch information
frostime committed Oct 14, 2024
1 parent d8a0e34 commit a5b6941
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "py-simple-inject"
version = "0.4.2"
version = "0.5.0"
description = "A lightweight dependency injection library for Python"
authors = [{ name = "frostime", email = "frostime@foxmail.com" }]
dependencies = []
Expand Down
8 changes: 7 additions & 1 deletion src/simple_inject/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ def provide(key: str, value: Any, namespace: str = 'default'):
__simple_inject.provide(key, value, namespace)


def inject(key: str, namespace: str = 'default', if_not_found: Literal['none', 'raise'] = 'none') -> Any:
def inject(
key: str, namespace: str = 'default', if_not_found: Literal['none', 'raise'] = 'none'
) -> Any:
"""
Inject a dependency.
Expand All @@ -45,6 +47,10 @@ def inject(key: str, namespace: str = 'default', if_not_found: Literal['none', '
return __simple_inject.inject(key, namespace, if_not_found)


def state(namespace: Optional[str] = None):
return __simple_inject.state(namespace)


def create_scope():
return __simple_inject.create_scope()

Expand Down
15 changes: 14 additions & 1 deletion src/simple_inject/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,12 @@ def provide(self, key: str, value: Any, namespace: str = 'default'):
context[namespace][key] = value
self._context.set(context)

def inject(self, key: str, namespace: str = 'default', if_not_found: Literal['none', 'raise'] = 'none') -> Any:
def inject(
self,
key: str,
namespace: str = 'default',
if_not_found: Literal['none', 'raise'] = 'none',
) -> Any:
"""
Inject a dependency.
Expand Down Expand Up @@ -88,6 +93,14 @@ def inject(self, key: str, namespace: str = 'default', if_not_found: Literal['no
f"Dependency '{key}' not found in namespace '{namespace}'"
)

@property
def state(self, namespace: Optional[str] = None):
all_context = self._context.get()
if namespace is None:
return all_context
else:
return all_context[namespace]

def create_scope(self):
"""
Create a new dependency scope.
Expand Down

0 comments on commit a5b6941

Please sign in to comment.