Injectinator 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ import functools # This is only needed for debugging, you can remove
2
+
3
+ def injectinator(func):
4
+ @functools.wraps(func) # This is only needed for debugging, you can remove
5
+ def wrapper(*args, **kwargs):
6
+ replacements = dict(zip(
7
+ func.__code__.co_varnames[:func.__code__.co_argcount],
8
+ list(([None] * func.__code__.co_argcount) + list(func.__defaults__ or []))[-func.__code__.co_argcount:]
9
+ ))
10
+ for position, default in enumerate(replacements.keys()):
11
+ if position >= len(args):
12
+ if default not in kwargs and isinstance(replacements[default], type):
13
+ kwargs[default] = replacements[default]()
14
+ return func(*args, **kwargs)
15
+ return wrapper
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: Injectinator
3
+ Version: 0.1.0
4
+ Summary: Very simple dependency injection
5
+ Author-email: Chris Read <centurix@gmail.com>
6
+ License: MIT
7
+ Project-URL: homepage, https://github.com/Centurix/injectinator
8
+ Project-URL: repository, https://github.com/Centurix/injectinator
9
+ Keywords: dependency,injection,di,decorator
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Natural Language :: English
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: Microsoft :: Windows
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Software Development :: Libraries
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+
22
+ ![build workflow](https://github.com/Centurix/injectinator/actions/workflows/test.yml/badge.svg)
23
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
24
+ ![uv-managed](https://img.shields.io/badge/uv-managed-blueviolet)
25
+
26
+ INJECTINATOR
27
+ =
28
+
29
+ Very Simple Dependency Injection.
30
+
31
+ Here's the function, just paste it where you need it:
32
+
33
+ ```
34
+ def injectinator(func):
35
+ def wrapper(*args, **kwargs):
36
+ replacements = dict(zip(
37
+ func.__code__.co_varnames[:func.__code__.co_argcount],
38
+ list(([None] * func.__code__.co_argcount) + list(func.__defaults__ or []))[-func.__code__.co_argcount:]
39
+ ))
40
+ for position, default in enumerate(replacements.keys()):
41
+ if position >= len(args):
42
+ if default not in kwargs and isinstance(replacements[default], type):
43
+ kwargs[default] = replacements[default]()
44
+ return func(*args, **kwargs)
45
+ return wrapper
46
+ ```
47
+
48
+ Need some kind of dependency injection but don't want a massive library adding to your
49
+ dependency graph that introduces potential supply chain attacks? Well, this is what you need.
50
+
51
+ This also doesn't need any imports to work. Just paste the script above here's an example of how to use it:
52
+
53
+ ```
54
+ class BaseClass:
55
+ # You don't really need this base class, but for the sake of method contracts it's here
56
+ def print(self):
57
+ ...
58
+
59
+ class InjectedClass(BaseClass):
60
+ # This will be the default injected class if nothing is provided in a call
61
+ def print(self):
62
+ print("Default class")
63
+
64
+
65
+ class SuppliedClass(BaseClass):
66
+ # This will be a supplied class
67
+ def print(self):
68
+ print("Supplied class")
69
+
70
+
71
+ @injectinator
72
+ def test(injected=InjectedClass):
73
+ # Can have as many parameters as you like, note that the class is a reference to the class, not an instance
74
+ injected.print()
75
+
76
+ # Two calls, first creates an instance of InjectedClass and passes it to the function, second supplies an instance of SuppliedClass
77
+ test()
78
+ test(SuppliedClass())
79
+ ```
80
+
81
+ Wait I hear you say: Can't we just create an instance of the class in the function specification like this?
82
+
83
+ ```
84
+ def test(injected=InjectedClass()):
85
+ ...
86
+ ```
87
+
88
+ You can, but the instantiation is performed when Python creates the definition of the function, not at the time you run
89
+ the function. Which means that the object it creates is re-used every time you call the function, which is not desirable.
90
+
91
+ Also, if you need to debug this, you might need to change it to:
92
+
93
+ ```
94
+ import functools
95
+
96
+ def injectinator(func):
97
+ @functools.wraps(func)
98
+ def wrapper(*args, **kwargs):
99
+ ...
100
+ ```
101
+
102
+ This will retain the call stack and debugging easier. But as the script is below, you can add it without imports.
103
+
104
+ Notes on this script
105
+ -
106
+
107
+ - It relies on dunder methods on `func` itself, so these _could_ change in the future. They've all been clumped up together for this reason to make it obvious when it fails because the Python foundation changed their usage of dunders
108
+ - There is no parameter support on the injected class, it could be adjusted to support them
109
+ - All the config for the injection is in the function specification rather than the decorator
110
+ - There's no types. It should have types I guess. Probably added to the two function specifications. Could be lazy and just make it all `Any` but then you'd have to drag in `typing` as an import for this gist
111
+ - I have not timed this. It could be wildly inefficient. There's an iteration enumerating over the function parameter list so its O(n)
112
+ - This script does work with arbitrary length argument specifications like adding `*args` to the end
113
+ - Although it is DI in 11 lines, I've no interest in code golf.
114
+
115
+ Operation
116
+ -
117
+
118
+ 1. Figure out what the default values are for each argument, dump the results in `replacements`
119
+ 1. Skip supplied positional values
120
+ 1. For arguments with a default value that do not have a keyword supplied value and the default is a class type, create an instance and add to the keyword argument dictionary
121
+ 1. Invoke the wrapped function/method with positional and keyword values
@@ -0,0 +1,5 @@
1
+ injectinator/__init__.py,sha256=RFmFNMTTY-SBYDZ6CVtyXtHdB5PN3h0x3wdjSOkiGlA,743
2
+ injectinator-0.1.0.dist-info/METADATA,sha256=x7jLR-X9NecuD43UlFmIJJovecjVTKHOb7FWQK6x4zM,4909
3
+ injectinator-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
4
+ injectinator-0.1.0.dist-info/top_level.txt,sha256=xJk9xaAcmNyJks9Ihr8ZC3fS-Kqi7Lv7EWhLCBtIgIM,13
5
+ injectinator-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ injectinator