Skip to content

Commit 612ecd6

Browse files
committed
Refactor Singleton/Factory with functools.partial
No need at the moment to keep track of the args and kwargs.
1 parent a288bbe commit 612ecd6

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

pif/providers.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
# https://github.com/scottzach1/python-injector-framework
1010

1111
import abc
12+
import functools
1213
from typing import Callable
1314

1415

@@ -46,17 +47,15 @@ class Singleton[T](Provider):
4647
Provide a singleton instance.
4748
"""
4849

49-
__slots__ = ("_func", "_args", "_kwargs", "_result", "_depends")
50+
__slots__ = ("_func", "_func", "_result", "_depends")
5051

5152
def __init__(self, func: Callable[[...], T], *args, **kwargs):
52-
self._func = func
53-
self._args = args
54-
self._kwargs = kwargs
53+
self._func = functools.partial(func, *args, **kwargs)
5554
self._result = UNSET
5655

5756
def __call__(self) -> T:
5857
if self._result is UNSET:
59-
self._result = self._func(*self._args, **self._kwargs)
58+
self._result = self._func()
6059
return self._result
6160

6261

@@ -65,12 +64,10 @@ class Factory[T](Provider):
6564
Generate a new instance every call.
6665
"""
6766

68-
__slots__ = ("_func", "_args", "_kwargs", "_depends")
67+
__slots__ = ("_func", "_depends")
6968

7069
def __init__(self, func: Callable[[...], T], *args, **kwargs):
71-
self._func = func
72-
self._args = args
73-
self._kwargs = kwargs
70+
self._func = functools.partial(func, *args, **kwargs)
7471

7572
def __call__(self) -> T:
76-
return self._func(*self._args, **self._kwargs)
73+
return self._func()

0 commit comments

Comments
 (0)