pyconject 0.1.0__tar.gz

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.1
2
+ Name: pyconject
3
+ Version: 0.1.0
4
+ Summary: pyconject --- a highly opinionated PYthon CONfig inJECTor library.
5
+ Author-email: "Edward L." <neolaw+pyconject@gmail.com>
6
+ Project-URL: Homepage, https://github.com/neolaw84/pyconject
7
+ Project-URL: Issues, https://github.com/neolaw84/pyconject/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+
15
+ # pyconject
16
+
17
+ `pyconject` is a (highly) opinionated PYthon CONfig inJECTor library inspired by Spring Framework (and Spring Boot Framework).
18
+
19
+ > **How to pronounce `pyconject`**
20
+ >
21
+ > `pyconject` is pronounced PY-CON-JECT, a word play for Burmese "ပိုက်ကွန်ချက်" = "the art of throwing net". It represents how it can be used to capture all types of configs and inject them into all types of packages.
22
+
23
+ # Usage
24
+
25
+ For detailed usage, refer to [usage.md](usage.md).
26
+
27
+ ## TL;DR
28
+
29
+ Instead of this:
30
+
31
+ ```python
32
+ # in usr_p/usr_sp/usr_m.py
33
+ from black_p.black_sp.black_m import black_func
34
+
35
+ # initialize values_a, value_b,
36
+ # value_c and value_d.
37
+ # this part is often the ugly mess
38
+ # because it involves reading yaml
39
+ # or other tree-like files and
40
+ # assigning values
41
+ import yaml
42
+ with open("./configs.yml", "rt") as f:
43
+ configs = yaml.safe_load(f)
44
+ black_func_parameters = configs["black_p"]["black_sp"]["black_m"]["black_func"]
45
+ value_a = black_func_parameters["a"]
46
+ # more ugly things here; you get the gist ...
47
+
48
+ black_func(a=value_a, b=value_b, c=value_c, d=value_d)
49
+ ```
50
+
51
+ With `pyconject`, we can do this:
52
+
53
+
54
+ ```python
55
+ # in usr_p/usr_sp/usr_m.py
56
+ from black_p.black_sp.black_m import black_func
57
+
58
+ # pyconject initializes values of a, b, c and d.
59
+ from pyconject import pyconject
60
+
61
+ pyconject.init(globals())
62
+
63
+ with pyconject.cntx():
64
+ black_func()
65
+ ```
66
+
67
+ ## Developing with `pyconject`
68
+
69
+ Instead of this:
70
+
71
+ ```python
72
+ # in dev_p/dev_sp/dev_m.py
73
+ import os
74
+
75
+ env = os.environ["environment"]
76
+
77
+ def dev_func(a=None, b=None, c=None, d=None):
78
+ if env == "dev":
79
+ if a is None: a = "dev-a"
80
+ if b is None: b = "dev-b"
81
+ # you know the rest
82
+ elif env == "stg":
83
+ if a is None: a = "stg-a"
84
+ if b is None: b = "stg-b"
85
+ # you know the rest
86
+ elif env == "prd":
87
+ if a is None: a = "prd-a"
88
+ if b is None: b = "prd-b"
89
+ # you know the rest
90
+ # ...
91
+ # your application logic
92
+ return results
93
+ ```
94
+
95
+ With `pyconject`, you can do this:
96
+
97
+ ```yaml
98
+ # in dev_p/dev_sp/pyconject-dev_m-dev.py
99
+ dev_func:
100
+ a : "dev-a"
101
+ b : "dev_b"
102
+ ...
103
+ ```
104
+
105
+ ```python
106
+ # in dev_p/dev_sp/dev_m.py
107
+ from pyconject import pyconject
108
+
109
+ @pyconject.func
110
+ def dev_func(a, b, c, d):
111
+ # your application logic
112
+ return results
113
+ ```
114
+
115
+ # To dos
116
+
117
+ * Developer integration
118
+ * ~~Functions~~ done
119
+ * Singletons/Classes
120
+ * ~~Modules~~ done
121
+ * ~~Packages~~ done
122
+
123
+ * Client integration
124
+ * ~~Functions~~ done
125
+ * Singletons/Classes
126
+ * ~~Modules~~
127
+ * ~~Packages~~
128
+ * ~~Auto-detect when cntx open~~ use `pyconject.init(globals())` instead
129
+
130
+ * Generate config files
131
+
132
+ * Raw retrieval of resolved configs (to manipulate by user)
133
+
134
+ * Type of configs
135
+ * ~~**yaml -- priority**~~ done
136
+ * ~~environment/target selection~~ done
137
+ * .env
138
+ * overrides
139
+ * environment variables
140
+ * commandline arguments
141
+
142
+ * Documentations
143
+ * ~~Usage~~ done
144
+
145
+ * CI/CD
146
+ * github actions to unittest at push and pull-request
147
+ * github actions to publish to pypi after merge
@@ -0,0 +1,133 @@
1
+ # pyconject
2
+
3
+ `pyconject` is a (highly) opinionated PYthon CONfig inJECTor library inspired by Spring Framework (and Spring Boot Framework).
4
+
5
+ > **How to pronounce `pyconject`**
6
+ >
7
+ > `pyconject` is pronounced PY-CON-JECT, a word play for Burmese "ပိုက်ကွန်ချက်" = "the art of throwing net". It represents how it can be used to capture all types of configs and inject them into all types of packages.
8
+
9
+ # Usage
10
+
11
+ For detailed usage, refer to [usage.md](usage.md).
12
+
13
+ ## TL;DR
14
+
15
+ Instead of this:
16
+
17
+ ```python
18
+ # in usr_p/usr_sp/usr_m.py
19
+ from black_p.black_sp.black_m import black_func
20
+
21
+ # initialize values_a, value_b,
22
+ # value_c and value_d.
23
+ # this part is often the ugly mess
24
+ # because it involves reading yaml
25
+ # or other tree-like files and
26
+ # assigning values
27
+ import yaml
28
+ with open("./configs.yml", "rt") as f:
29
+ configs = yaml.safe_load(f)
30
+ black_func_parameters = configs["black_p"]["black_sp"]["black_m"]["black_func"]
31
+ value_a = black_func_parameters["a"]
32
+ # more ugly things here; you get the gist ...
33
+
34
+ black_func(a=value_a, b=value_b, c=value_c, d=value_d)
35
+ ```
36
+
37
+ With `pyconject`, we can do this:
38
+
39
+
40
+ ```python
41
+ # in usr_p/usr_sp/usr_m.py
42
+ from black_p.black_sp.black_m import black_func
43
+
44
+ # pyconject initializes values of a, b, c and d.
45
+ from pyconject import pyconject
46
+
47
+ pyconject.init(globals())
48
+
49
+ with pyconject.cntx():
50
+ black_func()
51
+ ```
52
+
53
+ ## Developing with `pyconject`
54
+
55
+ Instead of this:
56
+
57
+ ```python
58
+ # in dev_p/dev_sp/dev_m.py
59
+ import os
60
+
61
+ env = os.environ["environment"]
62
+
63
+ def dev_func(a=None, b=None, c=None, d=None):
64
+ if env == "dev":
65
+ if a is None: a = "dev-a"
66
+ if b is None: b = "dev-b"
67
+ # you know the rest
68
+ elif env == "stg":
69
+ if a is None: a = "stg-a"
70
+ if b is None: b = "stg-b"
71
+ # you know the rest
72
+ elif env == "prd":
73
+ if a is None: a = "prd-a"
74
+ if b is None: b = "prd-b"
75
+ # you know the rest
76
+ # ...
77
+ # your application logic
78
+ return results
79
+ ```
80
+
81
+ With `pyconject`, you can do this:
82
+
83
+ ```yaml
84
+ # in dev_p/dev_sp/pyconject-dev_m-dev.py
85
+ dev_func:
86
+ a : "dev-a"
87
+ b : "dev_b"
88
+ ...
89
+ ```
90
+
91
+ ```python
92
+ # in dev_p/dev_sp/dev_m.py
93
+ from pyconject import pyconject
94
+
95
+ @pyconject.func
96
+ def dev_func(a, b, c, d):
97
+ # your application logic
98
+ return results
99
+ ```
100
+
101
+ # To dos
102
+
103
+ * Developer integration
104
+ * ~~Functions~~ done
105
+ * Singletons/Classes
106
+ * ~~Modules~~ done
107
+ * ~~Packages~~ done
108
+
109
+ * Client integration
110
+ * ~~Functions~~ done
111
+ * Singletons/Classes
112
+ * ~~Modules~~
113
+ * ~~Packages~~
114
+ * ~~Auto-detect when cntx open~~ use `pyconject.init(globals())` instead
115
+
116
+ * Generate config files
117
+
118
+ * Raw retrieval of resolved configs (to manipulate by user)
119
+
120
+ * Type of configs
121
+ * ~~**yaml -- priority**~~ done
122
+ * ~~environment/target selection~~ done
123
+ * .env
124
+ * overrides
125
+ * environment variables
126
+ * commandline arguments
127
+
128
+ * Documentations
129
+ * ~~Usage~~ done
130
+
131
+ * CI/CD
132
+ * github actions to unittest at push and pull-request
133
+ * github actions to publish to pypi after merge
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pyconject"
7
+ dynamic = ["version"]
8
+ authors = [
9
+ { name="Edward L.", email="neolaw+pyconject@gmail.com" },
10
+ ]
11
+ description = "pyconject --- a highly opinionated PYthon CONfig inJECTor library."
12
+ readme = "README.md"
13
+ requires-python = ">=3.9"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/neolaw84/pyconject"
22
+ Issues = "https://github.com/neolaw84/pyconject/issues"
23
+
24
+ [tool.setuptools.dynamic]
25
+ version = {attr = "pyconject.__version__"}
26
+
27
+ [tool.pytest.ini_options]
28
+ pythonpath = [
29
+ "src", "tests"
30
+ ]
31
+
32
+ [tool.bumpversion]
33
+ current_version = "0.1.0"
34
+ parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<micro>\\d+)"
35
+ serialize = ["{major}.{minor}.{micro}"]
36
+ search = "{current_version}"
37
+ replace = "{new_version}"
38
+ regex = false
39
+ ignore_missing_version = false
40
+ ignore_missing_files = false
41
+ tag = true
42
+ sign_tags = false
43
+ tag_name = "v{new_version}"
44
+ tag_message = "Bump version: {current_version} → {new_version}"
45
+ allow_dirty = false
46
+ commit = true
47
+ message = "Bump version: {current_version} → {new_version}"
48
+ commit_args = ""
49
+
50
+ [[tool.bumpversion.files]]
51
+ filename = "./src/pyconject/__init__.py"
52
+ search = "__version__ = '{current_version}'"
53
+ replace = "__version__ = '{new_version}'"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,84 @@
1
+ from copy import deepcopy
2
+ from pathlib import Path
3
+ import inspect
4
+ from .registry import Registry
5
+ from .utils import Stack, get_target_frame, load_and_merge_configs, get_imported_modules_and_funcs
6
+
7
+ # def _get_caller():
8
+ # """Retrieves the globals() dictionary of the caller's frame."""
9
+
10
+ # caller_frame = inspect.currentframe().f_back.f_back
11
+ # return caller_frame
12
+
13
+ class Cntx:
14
+ def __init__(self, target=None, config_path=None, cntx_stack=None):
15
+ self.cntx_stack = cntx_stack if cntx_stack else _cntx_stack
16
+
17
+ frame = inspect.currentframe()
18
+
19
+ while frame:
20
+ filename = inspect.getframeinfo(frame).filename
21
+ if not any(pattern in filename for pattern in ["<frozen importlib._bootstrap>", "<pytest", "<ipython-input-"]):
22
+ self.glb = frame.f_globals
23
+ break # Exit after modifying the first suitable frame
24
+ frame = frame.f_back
25
+
26
+ self.target = target
27
+ self.config_path = config_path
28
+
29
+ def __enter__(self):
30
+ self.cntx_stack.stack(target=self.target, config_path=self.config_path)
31
+
32
+ # new_globals = {n: self.cntx_stack.registry.register(v, by_dev=False) for n, v in self.glb.items()}
33
+ # for n, v in new_globals.items():
34
+ # self.glb[n] = v
35
+ return self
36
+
37
+ def __exit__(self, exc_type, exc_value, traceback):
38
+ self.cntx_stack.unstack()
39
+
40
+
41
+ class CntxStack:
42
+ _instance = None
43
+
44
+ def __new__(cls):
45
+ if cls._instance is None:
46
+ cls._instance = super(CntxStack, cls).__new__(cls)
47
+ return cls._instance
48
+
49
+ def __init__(self):
50
+ self.config_stack = Stack()
51
+ self.registry = Registry(self)
52
+
53
+ def _resolve_dev_configs(self, target):
54
+ dev_configs = self.registry.load_dev_configs(force=True, target=target)
55
+ self.config_stack.push(dev_configs)
56
+ return dev_configs
57
+
58
+ def stack(self, target=None, config_path=None):
59
+ prev_configs = self.config_stack.peek()
60
+ if prev_configs is None:
61
+ prev_configs = self._resolve_dev_configs(target)
62
+ # at this point, prev_configs is not None
63
+ configs = deepcopy(prev_configs)
64
+ if config_path is None:
65
+ config_path = "./configs.yml"
66
+ config_path = Path(config_path)
67
+ configs = load_and_merge_configs(config_path, configs)
68
+
69
+ if target is not None:
70
+ tgt_config_path = config_path.parent / f"{config_path.stem}-{target}{config_path.suffix}"
71
+ configs = load_and_merge_configs(tgt_config_path, configs)
72
+
73
+ self.config_stack.push(configs)
74
+
75
+ return configs
76
+
77
+ def get_configs(self):
78
+ return self.config_stack.peek() if len(self.config_stack) > 1 else {}
79
+
80
+ def unstack(self):
81
+ self.config_stack.pop()
82
+ if len(self.config_stack) == 1: self.config_stack.pop()
83
+
84
+ _cntx_stack = CntxStack()
@@ -0,0 +1,19 @@
1
+ import functools
2
+
3
+ from .context import _cntx_stack, Cntx
4
+
5
+ def func(_func=None):
6
+ return functools.partial(_cntx_stack.registry.register, by_dev=True) \
7
+ if _func is None \
8
+ else _cntx_stack.registry.register(_func, by_dev=True)
9
+
10
+ def mdle(_mdle:str):
11
+ return _cntx_stack.registry.register(_mdle, by_dev=True)
12
+
13
+ def init(caller_globals):
14
+ new_globals = {n: _cntx_stack.registry.register(v, by_dev=False) for n, v in caller_globals.items()}
15
+ caller_globals.update(new_globals)
16
+
17
+ def cntx(config_path=None, target=None):
18
+ cntx = Cntx(target=target, config_path=config_path)
19
+ return cntx
@@ -0,0 +1,244 @@
1
+
2
+ from __future__ import annotations
3
+
4
+ import importlib
5
+ from enum import Enum
6
+
7
+ import functools
8
+ import inspect
9
+ from pathlib import Path
10
+ from typing import Callable, Dict, Union, List
11
+
12
+ from abc import ABC, abstractmethod
13
+
14
+ from .utils import get_from_prefixed_tree, get_subs, init_default_dev_configs, load_and_merge_configs
15
+
16
+ def _check_if_method(func: Callable):
17
+ return hasattr(func, "__self__") and getattr(func, "__self__", None) is not None
18
+
19
+ class RegItemType(Enum):
20
+ UNKN = 0
21
+ FUNC = 1
22
+ MTHD = 2
23
+ MODL = 3
24
+ PKGE = 4
25
+
26
+ class RegItem(ABC):
27
+ def __init__(self, item: Union[Callable, str], reg_item_type:RegItemType, file_path:Path, m):
28
+ self.item = item
29
+ self.reg_item_type = reg_item_type
30
+ self.file_path = file_path
31
+ # self.configs = configs
32
+ self.m = m
33
+ self.cname = self.get_cname()
34
+ self.prefix = self.get_prefix()
35
+
36
+ @abstractmethod
37
+ def get_cname(self):
38
+ raise NotImplementedError("Entry is an abstract class and hasn't implemented get_cname.")
39
+
40
+ def __eq__(self, value: object) -> bool:
41
+ if not isinstance(value, RegItem): return False
42
+ return all(
43
+ self.item == value.item,
44
+ self.reg_item_type == value.reg_item_type,
45
+ self.file_path == value.file_path,
46
+ # self.configs == value.configs,
47
+ self.m == value.m,
48
+ self.cname == value.cname
49
+ )
50
+
51
+ @abstractmethod
52
+ def get_dev_config_paths(self):
53
+ raise NotImplementedError("entry is an abstract class and hasn't implemented get_dev_config_paths.")
54
+
55
+ @abstractmethod
56
+ def get_prefix(self):
57
+ raise NotImplementedError("entry is an abstract class and hasn't implemented get_prefix.")
58
+
59
+ class Function(RegItem):
60
+ def get_cname(self):
61
+ return (self.item.__module__, self.item.__qualname__)
62
+
63
+ def get_dev_config_paths(self):
64
+ configs_parent = Path(self.m.__file__).parent
65
+
66
+ dev_configs = None
67
+ if hasattr(self.item, "pyconject"): dev_configs = getattr(self.item, "pyconject")
68
+
69
+ if isinstance(dev_configs, str):
70
+ cfg_path = Path(dev_configs)
71
+ return init_default_dev_configs(configs_parent, cfg_path.stem, cfg_path.suffix)
72
+
73
+ base_file = "-".join(["pyconject", self.cname[0].split(".")[-1], self.cname[1]])
74
+ _temp_dict = init_default_dev_configs(configs_parent, base_file)
75
+
76
+ if isinstance(dev_configs, dict):
77
+ for k, v in dev_configs.items():
78
+ _temp_dict[k] = str(configs_parent / v)
79
+
80
+ return _temp_dict # this also covers when self.configs is None
81
+
82
+ def get_prefix(self):
83
+ return ".".join(self.cname) if self.reg_item_type == RegItemType.FUNC else ".".join((self.cname[0], self.cname[1].replace(".", "-")))
84
+
85
+ class Module(RegItem):
86
+ def get_cname(self):
87
+ parts = self.m.__name__.split(".")
88
+ return (".".join(parts[:-1]), parts[-1])
89
+
90
+ def get_dev_config_paths(self):
91
+ configs_parent = Path(self.m.__file__).parent
92
+
93
+ dev_configs = None
94
+ if hasattr(self.m, "pyconject"): dev_configs = getattr(self.m, "pyconject")
95
+
96
+ if isinstance(dev_configs, str):
97
+ cfg_path = Path(dev_configs)
98
+ return init_default_dev_configs(configs_parent, cfg_path.stem, cfg_path.suffix)
99
+
100
+ base_file = "-".join(["pyconject", self.cname[1]])
101
+ _temp_dict = init_default_dev_configs(configs_parent, base_file)
102
+
103
+ if isinstance(dev_configs, dict):
104
+ for k, v in dev_configs.items():
105
+ _temp_dict[k] = str(configs_parent / v)
106
+
107
+ return _temp_dict # this also covers when self.configs is None
108
+
109
+ def get_prefix(self):
110
+ return ".".join(self.cname) if self.reg_item_type == RegItemType.FUNC else ".".join((self.cname[0], self.cname[1].replace(".", "-")))
111
+
112
+ class Package(RegItem):
113
+ def get_cname(self):
114
+ parts = self.m.__name__.split(".")
115
+ return (".".join(parts[:-1]), parts[-1])
116
+
117
+ def get_dev_config_paths(self):
118
+ configs_parent = Path(self.m.__file__).parent
119
+
120
+ dev_configs = None
121
+ if hasattr(self.m, "pyconject"): dev_configs = getattr(self.m, "pyconject")
122
+
123
+ if isinstance(dev_configs, str):
124
+ cfg_path = Path(dev_configs)
125
+ return init_default_dev_configs(configs_parent, cfg_path.stem, cfg_path.suffix)
126
+
127
+ base_file = "pyconject"
128
+ _temp_dict = init_default_dev_configs(configs_parent, base_file)
129
+
130
+ if isinstance(dev_configs, dict):
131
+ for k, v in dev_configs.items():
132
+ _temp_dict[k] = str(configs_parent / v)
133
+
134
+ return _temp_dict # this also covers when dev_configs is None
135
+
136
+ def get_prefix(self):
137
+ return ".".join(self.cname) if self.reg_item_type == RegItemType.FUNC else ".".join((self.cname[0], self.cname[1].replace(".", "-")))
138
+
139
+ def _create_reg_item(item)->RegItem:
140
+ try:
141
+ reg_item_type, file_path, m = RegItemType.UNKN, None, None
142
+ if callable(item):
143
+ m = importlib.import_module(item.__module__)
144
+ file_path = Path(m.__file__)
145
+ reg_item_type = RegItemType.MTHD if _check_if_method(item) else RegItemType.FUNC
146
+ else: # package or sub-module registration
147
+ if isinstance(item, str): # package/module registration by name
148
+ m = importlib.import_module(item)
149
+ else: # package/module registration by package/module itself
150
+ m = item
151
+ item = f"{m.__module__}.{m.__name__}"
152
+ file_path = Path(m.__file__)
153
+ reg_item_type = RegItemType.PKGE if file_path.stem == "__init__" else RegItemType.MODL
154
+ finally:
155
+ entry_type_to_entry_class: Dict[RegItemType, RegItem] = {
156
+ RegItemType.FUNC : Function,
157
+ RegItemType.MTHD : Function,
158
+ RegItemType.MODL : Module,
159
+ RegItemType.PKGE : Package
160
+ }
161
+ Ent: RegItem = entry_type_to_entry_class.get(reg_item_type, None)
162
+ if Ent: return Ent(item, reg_item_type, file_path, m)
163
+
164
+ def _register_func(f, cntx_stack):
165
+ @functools.wraps(f)
166
+ def wrapper_func(*args, **kwargs):
167
+ # Get the function signature.
168
+ sig = inspect.signature(f)
169
+
170
+ # Bind the given arguments to the function signature.
171
+ bound_args = sig.bind_partial(*args, **kwargs)
172
+
173
+ # Iterate over the parameters in the function signature.
174
+ reg_item = _create_reg_item(item=f)
175
+ configs = cntx_stack.get_configs()
176
+ kw_args = get_from_prefixed_tree(prefix=reg_item.prefix, tree=configs)
177
+ if kw_args:
178
+ for param_name, param in sig.parameters.items():
179
+ # If a parameter is missing from the bound arguments
180
+ # and present in the configs in the dictionary at top
181
+ # of cntx_stack, use the value from the dictionary.
182
+
183
+ if param_name not in bound_args.arguments and param_name in kw_args:
184
+ kwargs[param_name] = kw_args[param_name]
185
+ value = f(*args, **kwargs)
186
+ return value
187
+ return wrapper_func
188
+
189
+ class Registry:
190
+
191
+ def __init__(self, cntx_stack):
192
+ self._cntx_stack = cntx_stack
193
+ self._registry = {}
194
+ self._loaded_dev_configs = None
195
+
196
+ def _register(self, item: Union[Callable,str], dev_override:bool=False) -> None:
197
+ # override is for dev registration only;
198
+ # if it is by client, it does not matter
199
+ entry_inst = _create_reg_item(item=item)
200
+
201
+ if entry_inst is None: return item # can't do anything here
202
+
203
+ prefix = entry_inst.prefix
204
+
205
+ # dev_override means direct dev call
206
+ if prefix not in self._registry.keys() or dev_override:
207
+ self._registry[prefix] = entry_inst
208
+
209
+ if entry_inst.reg_item_type in [RegItemType.FUNC, RegItemType.MTHD]:
210
+ entry_inst.item = _register_func(f=entry_inst.item, cntx_stack=self._cntx_stack)
211
+
212
+ if entry_inst.reg_item_type in [RegItemType.MODL, RegItemType.PKGE]:
213
+ # recursively register all sub-modules
214
+ _subs = {sub_name: self._register(sub) for sub_name, sub in get_subs(entry_inst.m)}
215
+
216
+ for sn, sv in _subs.items():
217
+ vars(entry_inst.m)[sn] = sv
218
+
219
+ return self._registry[prefix].item
220
+
221
+ def register(self, item: Union[Callable, str], by_dev:bool=True) -> None:
222
+ try:
223
+ return self._register(item, dev_override=by_dev)
224
+ except:
225
+ return item
226
+
227
+ def load_dev_configs(self, force=False, target=None) -> Dict:
228
+ if self._loaded_dev_configs is not None and not force:
229
+ return self._loaded_dev_configs
230
+
231
+ sorted_prefixes = sorted([prefix for prefix in self._registry.keys()], key=lambda x : len(".".join(x).split(".")))
232
+
233
+ sorted_reg_items : List[RegItem] = [self._registry[prefix] for prefix in sorted_prefixes]
234
+
235
+ configs = {}
236
+ for reg_item in sorted_reg_items:
237
+ dev_config_path = reg_item.get_dev_config_paths()
238
+ configs = load_and_merge_configs(dev_config_path[""], configs, reg_item.prefix)
239
+
240
+ if target is not None and target in dev_config_path:
241
+ configs = load_and_merge_configs(dev_config_path[target], configs, reg_item.prefix)
242
+
243
+ self._loaded_dev_configs = configs
244
+ return configs
@@ -0,0 +1,97 @@
1
+ from typing import Dict
2
+
3
+ import inspect
4
+ import yaml
5
+
6
+ def merge_dictionaries(dict1, dict2):
7
+ merged = dict1.copy()
8
+ for key, value in dict2.items():
9
+ if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
10
+ merged[key] = merge_dictionaries(merged[key], value)
11
+ else:
12
+ merged[key] = value
13
+ return merged
14
+
15
+
16
+ def create_prefixed_tree(cfg: Dict, prefix: str) -> Dict:
17
+ parts = prefix.split(".")
18
+ tree = cfg
19
+ for part in reversed(parts):
20
+ if part != "": tree = {part: tree}
21
+ return tree
22
+
23
+ def get_from_prefixed_tree(tree: Dict, prefix: str):
24
+ parts = prefix.split(".")
25
+ for part in parts:
26
+ if isinstance(tree, dict) and part in tree:
27
+ tree = tree[part]
28
+ else:
29
+ return {} # Prefix not found
30
+ return tree
31
+
32
+
33
+ def init_default_dev_configs(configs_parent, base_file_stem, base_file_ext=".yml"):
34
+ _dict = {t: str(configs_parent / ("-".join([base_file_stem, t]) + base_file_ext)) for t in ["stg", "dev", "prd"]}
35
+ _dict[""] = str(configs_parent / base_file_stem) + base_file_ext
36
+ return _dict
37
+
38
+
39
+ def load_and_merge_configs(config_path, configs, prefix=""):
40
+ try:
41
+ with open(config_path, "rt") as f:
42
+ cfgs = yaml.safe_load(f)
43
+ tmp = create_prefixed_tree(cfgs, prefix)
44
+ configs = merge_dictionaries(configs, tmp)
45
+ except:
46
+ pass
47
+ return configs
48
+
49
+ def get_target_frame(num_back=2):
50
+ target_frame = inspect.currentframe()
51
+ for _ in range(num_back + 1): # +1 to account for the function itself
52
+ if target_frame is None:
53
+ break
54
+ target_frame = target_frame.f_back
55
+ return target_frame
56
+
57
+ def get_imported_modules_and_funcs(num_back=2):
58
+ target_frame = get_target_frame(num_back)
59
+
60
+ if target_frame is None:
61
+ return {} # Return an empty dictionary if the frame is not found
62
+
63
+ # Retrieve the target frame's local variables.
64
+ mods_and_funcs = {k: v for k, v in target_frame.f_globals.items() if callable(v) or inspect.ismodule(v)}
65
+
66
+ return mods_and_funcs
67
+ # mods_and_funs = {k: v for k, v in globals().items() if callable(v) or inspect.ismodule(v)}
68
+ # return mods_and_funs
69
+
70
+ def get_subs(module):
71
+ def _is_interest(v):
72
+ return (inspect.ismodule(v) and inspect.getmodule(v) is module) or \
73
+ ((inspect.isfunction(v) or inspect.ismethod(v)) and inspect.getmodule(v) is module)
74
+ return {n: v for n, v in vars(module).items() if _is_interest(v)}
75
+
76
+ class Stack:
77
+ def __init__(self):
78
+ self._items = []
79
+
80
+ def __len__(self):
81
+ return len(self._items)
82
+
83
+ def is_empty(self):
84
+ return len(self._items) == 0
85
+
86
+ def pop(self):
87
+ if self.is_empty():
88
+ raise IndexError("Cannot pop from an empty stack")
89
+ return self._items.pop()
90
+
91
+ def push(self, item):
92
+ self._items.append(item)
93
+
94
+ def peek(self):
95
+ if self.is_empty():
96
+ return None
97
+ return self._items[-1]
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.1
2
+ Name: pyconject
3
+ Version: 0.1.0
4
+ Summary: pyconject --- a highly opinionated PYthon CONfig inJECTor library.
5
+ Author-email: "Edward L." <neolaw+pyconject@gmail.com>
6
+ Project-URL: Homepage, https://github.com/neolaw84/pyconject
7
+ Project-URL: Issues, https://github.com/neolaw84/pyconject/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+
15
+ # pyconject
16
+
17
+ `pyconject` is a (highly) opinionated PYthon CONfig inJECTor library inspired by Spring Framework (and Spring Boot Framework).
18
+
19
+ > **How to pronounce `pyconject`**
20
+ >
21
+ > `pyconject` is pronounced PY-CON-JECT, a word play for Burmese "ပိုက်ကွန်ချက်" = "the art of throwing net". It represents how it can be used to capture all types of configs and inject them into all types of packages.
22
+
23
+ # Usage
24
+
25
+ For detailed usage, refer to [usage.md](usage.md).
26
+
27
+ ## TL;DR
28
+
29
+ Instead of this:
30
+
31
+ ```python
32
+ # in usr_p/usr_sp/usr_m.py
33
+ from black_p.black_sp.black_m import black_func
34
+
35
+ # initialize values_a, value_b,
36
+ # value_c and value_d.
37
+ # this part is often the ugly mess
38
+ # because it involves reading yaml
39
+ # or other tree-like files and
40
+ # assigning values
41
+ import yaml
42
+ with open("./configs.yml", "rt") as f:
43
+ configs = yaml.safe_load(f)
44
+ black_func_parameters = configs["black_p"]["black_sp"]["black_m"]["black_func"]
45
+ value_a = black_func_parameters["a"]
46
+ # more ugly things here; you get the gist ...
47
+
48
+ black_func(a=value_a, b=value_b, c=value_c, d=value_d)
49
+ ```
50
+
51
+ With `pyconject`, we can do this:
52
+
53
+
54
+ ```python
55
+ # in usr_p/usr_sp/usr_m.py
56
+ from black_p.black_sp.black_m import black_func
57
+
58
+ # pyconject initializes values of a, b, c and d.
59
+ from pyconject import pyconject
60
+
61
+ pyconject.init(globals())
62
+
63
+ with pyconject.cntx():
64
+ black_func()
65
+ ```
66
+
67
+ ## Developing with `pyconject`
68
+
69
+ Instead of this:
70
+
71
+ ```python
72
+ # in dev_p/dev_sp/dev_m.py
73
+ import os
74
+
75
+ env = os.environ["environment"]
76
+
77
+ def dev_func(a=None, b=None, c=None, d=None):
78
+ if env == "dev":
79
+ if a is None: a = "dev-a"
80
+ if b is None: b = "dev-b"
81
+ # you know the rest
82
+ elif env == "stg":
83
+ if a is None: a = "stg-a"
84
+ if b is None: b = "stg-b"
85
+ # you know the rest
86
+ elif env == "prd":
87
+ if a is None: a = "prd-a"
88
+ if b is None: b = "prd-b"
89
+ # you know the rest
90
+ # ...
91
+ # your application logic
92
+ return results
93
+ ```
94
+
95
+ With `pyconject`, you can do this:
96
+
97
+ ```yaml
98
+ # in dev_p/dev_sp/pyconject-dev_m-dev.py
99
+ dev_func:
100
+ a : "dev-a"
101
+ b : "dev_b"
102
+ ...
103
+ ```
104
+
105
+ ```python
106
+ # in dev_p/dev_sp/dev_m.py
107
+ from pyconject import pyconject
108
+
109
+ @pyconject.func
110
+ def dev_func(a, b, c, d):
111
+ # your application logic
112
+ return results
113
+ ```
114
+
115
+ # To dos
116
+
117
+ * Developer integration
118
+ * ~~Functions~~ done
119
+ * Singletons/Classes
120
+ * ~~Modules~~ done
121
+ * ~~Packages~~ done
122
+
123
+ * Client integration
124
+ * ~~Functions~~ done
125
+ * Singletons/Classes
126
+ * ~~Modules~~
127
+ * ~~Packages~~
128
+ * ~~Auto-detect when cntx open~~ use `pyconject.init(globals())` instead
129
+
130
+ * Generate config files
131
+
132
+ * Raw retrieval of resolved configs (to manipulate by user)
133
+
134
+ * Type of configs
135
+ * ~~**yaml -- priority**~~ done
136
+ * ~~environment/target selection~~ done
137
+ * .env
138
+ * overrides
139
+ * environment variables
140
+ * commandline arguments
141
+
142
+ * Documentations
143
+ * ~~Usage~~ done
144
+
145
+ * CI/CD
146
+ * github actions to unittest at push and pull-request
147
+ * github actions to publish to pypi after merge
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/pyconject/__init__.py
5
+ src/pyconject/context.py
6
+ src/pyconject/pyconject.py
7
+ src/pyconject/registry.py
8
+ src/pyconject/utils.py
9
+ src/pyconject.egg-info/PKG-INFO
10
+ src/pyconject.egg-info/SOURCES.txt
11
+ src/pyconject.egg-info/dependency_links.txt
12
+ src/pyconject.egg-info/top_level.txt
13
+ tests/test_client_usages.py
14
+ tests/test_dev_usages.py
@@ -0,0 +1 @@
1
+ pyconject
@@ -0,0 +1,108 @@
1
+ import os
2
+ from unittest import TestCase
3
+ from unittest.mock import patch
4
+ import tempfile
5
+ from pathlib import Path
6
+ import yaml
7
+
8
+ from pyconject import pyconject
9
+
10
+ from unittest_utils import get_dynamic_mock_open, remove_file_or_directory
11
+ from black_p.black_sp.black_m import black_func
12
+ from dev_p.dev_sp.dev_m import dev_func_m
13
+
14
+ class ClientUsageTest(TestCase):
15
+
16
+ def setUp(self):
17
+ self.configs = yaml.dump({
18
+ "black_p": {
19
+ "black_sp": {
20
+ "black_m": {
21
+ "black_func": {
22
+ "b": "clt-defined-in-configs-b",
23
+ "c": "clt-defined-in-configs-c"
24
+ }
25
+ }
26
+ }
27
+ }
28
+ })
29
+ self.configs_dev = yaml.dump({
30
+ "black_p": {
31
+ "black_sp": {
32
+ "black_m": {
33
+ "black_func": {
34
+ "c": "clt-defined-in-configs-dev-c"
35
+ }
36
+ }
37
+ }
38
+ }
39
+ })
40
+ with open("tests/cfgs.yml", "wt") as f:
41
+ yaml.safe_dump({
42
+ "dev_p": {
43
+ "dev_sp": {
44
+ "dev_m": {
45
+ "dev_func_m": {
46
+ "a": "a1"
47
+ }
48
+ }
49
+ }
50
+ }
51
+ }, f)
52
+
53
+ def tearDown(self) -> None:
54
+ remove_file_or_directory(Path("tests/cfgs.yml"))
55
+ return super().tearDown()
56
+
57
+ def test_vanilla(self):
58
+ with self.assertRaises(TypeError):
59
+ black_func()
60
+
61
+ a, b, c, d = black_func(1, 2, 3)
62
+ assert (a, b, c, d) == (1, 2, 3, "dev-default-in-func-definion")
63
+
64
+ def test_cntx_default(self):
65
+ with patch("builtins.open", get_dynamic_mock_open({
66
+ (Path("./configs.yml"), "rt") : self.configs,
67
+ (Path("./configs-dev.yml"), "rt") : self.configs_dev
68
+ })):
69
+ pyconject.init(globals())
70
+ with pyconject.cntx():
71
+ a, b, c, d = black_func(1, 2)
72
+ assert (a, b, c, d) == (1, 2, "clt-defined-in-configs-c", "dev-default-in-func-definion")
73
+
74
+ def test_cntx_target_dev(self):
75
+ with patch("builtins.open", get_dynamic_mock_open({
76
+ (Path("./configs.yml"), "rt") : self.configs,
77
+ (Path("./configs-dev.yml"), "rt") : self.configs_dev
78
+ })):
79
+ pyconject.init(globals())
80
+ with pyconject.cntx(target="dev"):
81
+ a, b, c, d = black_func(1, 2)
82
+ assert (a, b, c, d) == (1, 2, "clt-defined-in-configs-dev-c", "dev-default-in-func-definion")
83
+
84
+ def test_cntx_custom_cfg_files(self):
85
+ with patch("builtins.open", get_dynamic_mock_open({
86
+ (Path("./cfgs.yml"), "rt") : self.configs,
87
+ (Path("./cfgs-dev.yml"), "rt") : self.configs_dev
88
+ })):
89
+ pyconject.init(globals())
90
+ with pyconject.cntx(config_path="cfgs.yml"):
91
+ a, b, c, d = black_func(1, 2)
92
+ assert (a, b, c, d) == (1, 2, "clt-defined-in-configs-c", "dev-default-in-func-definion")
93
+
94
+ def test_cntx_custom_cfg_files_target_dev(self):
95
+ with patch("builtins.open", get_dynamic_mock_open({
96
+ (Path("./cfgs.yml"), "rt") : self.configs,
97
+ (Path("./cfgs-dev.yml"), "rt") : self.configs_dev
98
+ })):
99
+ pyconject.init(globals())
100
+ with pyconject.cntx(config_path="cfgs.yml", target="dev"):
101
+ a, b, c, d = black_func(1, 2)
102
+ assert (a, b, c, d) == (1, 2, "clt-defined-in-configs-dev-c", "dev-default-in-func-definion")
103
+
104
+ def test_cntx_default_m_func(self):
105
+ pyconject.init(globals())
106
+ with pyconject.cntx(config_path="tests/cfgs.yml"):
107
+ a, b, c, d = dev_func_m()
108
+ assert (a, b, c, d) == ("a1", 20002, 3003, 404)
@@ -0,0 +1,84 @@
1
+ import os
2
+ from unittest import TestCase
3
+ from unittest.mock import patch
4
+ import tempfile
5
+ from pathlib import Path
6
+ import yaml
7
+
8
+ # import pyconject as root_pyconject
9
+ from pyconject import pyconject
10
+
11
+ from unittest_utils import get_dynamic_mock_open
12
+ from dev_p.dev_sp.dev_m import dev_func, dev_func_sp, dev_func_m, dev_func_sp_custom, dev_func_sp_custom2
13
+
14
+ class DevUsageTest(TestCase):
15
+
16
+ def test_vanilla(self):
17
+ with self.assertRaises(TypeError):
18
+ dev_func()
19
+
20
+ a, b, c, d = dev_func(1, 2, 3)
21
+ assert (a, b, c, d) == (1, 2, 3, "dev-default-in-func-definion")
22
+
23
+ def test_cntx_default(self):
24
+ pyconject.init(globals())
25
+ with pyconject.cntx():
26
+ a, b, c, d = dev_func(1, 2)
27
+ assert (a, b, c, d) == (1, 2, 303, 404)
28
+
29
+ def test_cntx_target_dev(self):
30
+ pyconject.init(globals())
31
+ with pyconject.cntx(target="dev"):
32
+ a, b, c, d = dev_func(1, 2)
33
+ assert (a, b, c, d) == (1, 2, 303, "404-dev")
34
+
35
+ def test_cntx_default_sp(self):
36
+ pyconject.init(globals())
37
+ with pyconject.cntx():
38
+ a, b, c, d = dev_func_sp(1, 2)
39
+ assert (a, b, c, d) == (1, 2, 3003, 404)
40
+
41
+ def test_cntx_target_dev_sp(self):
42
+ pyconject.init(globals())
43
+ with pyconject.cntx(target="dev"):
44
+ a, b, c, d = dev_func_sp(1)
45
+ assert (a, b, c, d) == (1, 2002, "3003-dev", "404-dev")
46
+
47
+ def test_cntx_default_m_func(self):
48
+ pyconject.init(globals())
49
+ with pyconject.cntx():
50
+ a, b, c, d = dev_func_m()
51
+ assert (a, b, c, d) == (100001, 20002, 3003, 404)
52
+
53
+ def test_cntx_default_m_func_custom(self):
54
+ pyconject.init(globals())
55
+ with pyconject.cntx():
56
+ a, b, c, d = dev_func_sp_custom()
57
+ assert (a, b, c, d) == (11, 22, "c", "d")
58
+
59
+ def test_cntx_default_m_func_custom2(self):
60
+ pyconject.init(globals())
61
+ with pyconject.cntx(target="dev"):
62
+ a, b, c, d = dev_func_sp_custom2()
63
+ assert (a, b, c, d) == (111, 22, "cc", "dd")
64
+
65
+ # def test_cntx_custom_cfg_files(self):
66
+ # with patch("builtins.open", get_dynamic_mock_open({
67
+ # (Path("./cfgs.yml"), "rt") : self.configs,
68
+ # (Path("./cfgs-dev.yml"), "rt") : self.configs_dev
69
+ # })):
70
+ # pyconject.init(globals())
71
+ # with pyconject.cntx(config_path="cfgs.yml"):
72
+ # a, b, c, d = dev_func(1, 2)
73
+ # assert (a, b, c, d) == (1, 2, "clt-defined-in-configs-c", "dev-default-in-func-definion")
74
+
75
+ # def test_cntx_custom_cfg_files_target_dev(self):
76
+ # with patch("builtins.open", get_dynamic_mock_open({
77
+ # (Path("./cfgs.yml"), "rt") : self.configs,
78
+ # (Path("./cfgs-dev.yml"), "rt") : self.configs_dev
79
+ # })):
80
+ # pyconject.init(globals())
81
+ # with pyconject.cntx(config_path="cfgs.yml", target="dev"):
82
+ # a, b, c, d = dev_func(1, 2)
83
+ # assert (a, b, c, d) == (1, 2, "clt-defined-in-configs-dev-c", "dev-default-in-func-definion")
84
+