spArgValidatorPy 1.0.1__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,220 @@
1
+ # ================================================================================
2
+ #
3
+ # ArgValidator class
4
+ #
5
+ # object for validating function arguments and either raising an exception
6
+ # or returning the validated value
7
+ #
8
+ # MIT License
9
+ #
10
+ # Copyright (c) 2025 krokoreit (krokoreit@gmail.com)
11
+ #
12
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ # of this software and associated documentation files (the "Software"), to deal
14
+ # in the Software without restriction, including without limitation the rights
15
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ # copies of the Software, and to permit persons to whom the Software is
17
+ # furnished to do so, subject to the following conditions:
18
+ #
19
+ # The above copyright notice and this permission notice shall be included in all
20
+ # copies or substantial portions of the Software.
21
+ #
22
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ # SOFTWARE.
29
+ #
30
+ # ================================================================================
31
+
32
+ import sys
33
+ import inspect
34
+
35
+
36
+ original_excepthook = sys.excepthook
37
+ stop_TB_at_function_name = None
38
+ def my_excepthook(type, value, traceback):
39
+ """A replacement for sys.excepthook to stop traceback output at stop_TB_at_function_name."""
40
+ print("my_excepthook")
41
+ iter_tb = traceback
42
+ while iter_tb.tb_next is not None:
43
+ if iter_tb.tb_next.tb_frame.f_code.co_name is stop_TB_at_function_name:
44
+ iter_tb.tb_next = None
45
+ break
46
+ iter_tb = iter_tb.tb_next
47
+ original_excepthook(type, value, traceback)
48
+
49
+ # shift to my handler
50
+ sys.excepthook = my_excepthook
51
+
52
+ def raise_with_stopped_traceback(exception_type, exception_text):
53
+ """Raises an exception of exception_type with a formated text with name and signature of the 'error function' and exception_text.
54
+ Traceback will be stopped at that function."""
55
+ global stop_TB_at_function_name
56
+
57
+ frame = inspect.currentframe().f_back.f_back
58
+ function_name = frame.f_code.co_name
59
+ stop_TB_at_function_name = function_name
60
+ function = None
61
+ if "self" in frame.f_locals:
62
+ function = getattr(frame.f_locals["self"].__class__, function_name)
63
+ else:
64
+ function = getattr(inspect.getmodule(frame), function_name)
65
+ if function is None:
66
+ sig = "()"
67
+ else:
68
+ sig = inspect.signature(function)
69
+ raise exception_type(function_name + str(sig) + " " + exception_text)
70
+
71
+ def reset_traceback():
72
+ """Resets the stop_TB_at_function_name to None. This is to prevent unintended stopping of traceback information. This would occur
73
+ when a raise_with_stopped_traceback() created exception gets caught with a try-except-block and a subsequent exception
74
+ occurs with the stop_TB_at_function_name still being on the calling stack ... Call reset_traceback() at start of each validation."""
75
+
76
+ def get_value_for_var_name(var_name):
77
+ """Returns the value for the variable named var_name."""
78
+ frame = inspect.currentframe().f_back
79
+ local_vars = frame.f_back.f_locals
80
+ if len(var_name) == 0:
81
+ raise_with_stopped_traceback(ValueError, "called without var_name, must be one of " + str(local_vars.keys()) + ".")
82
+ if var_name not in local_vars:
83
+ raise_with_stopped_traceback(ValueError, "called with unknown var_name '" + var_name + "', must be one of " + str(local_vars.keys()) + ".")
84
+ return local_vars[var_name]
85
+
86
+
87
+ class ArgValidator:
88
+
89
+ def get_validated_int(self, var_name, min_value=None, max_value=None, strict=False, *, default=None, return_limits=False):
90
+ """Returns a validated integer value or raises exception. Optional checking for limits (min_value, max_value) or in strict
91
+ mode (not allowing string representation of an integer). Specifying an integer value with default=[int] or setting
92
+ return_limits=True will prohibit an exception being raised and the default or exceeded limit value is returned."""
93
+
94
+ reset_traceback()
95
+ if default is not None and not isinstance(default, int):
96
+ raise_with_stopped_traceback(TypeError, "called with 'default' not being an integer.")
97
+
98
+ value = get_value_for_var_name(var_name)
99
+ # might be string representation
100
+ if isinstance(value, str):
101
+ if strict:
102
+ if default is not None:
103
+ return default
104
+ raise_with_stopped_traceback(TypeError, "called with '" + var_name + "' not being a string.")
105
+ else:
106
+ sValue = value.strip()
107
+ try:
108
+ value = int(sValue)
109
+ if str(value) != sValue:
110
+ value = None
111
+ except Exception as e:
112
+ value = None
113
+ if not isinstance(value, int):
114
+ if default is not None:
115
+ return default
116
+ raise_with_stopped_traceback(TypeError, "called with '" + var_name + "' not being an integer or a string representation of an integer.")
117
+ if min_value is not None and value < min_value:
118
+ if return_limits:
119
+ return min_value
120
+ if default is not None:
121
+ return default
122
+ raise_with_stopped_traceback(ValueError, "called with '" + var_name + "' being less than minimum value of " + str(min_value) + ".")
123
+ if max_value is not None and value > max_value:
124
+ if return_limits:
125
+ return max_value
126
+ if default is not None:
127
+ return default
128
+ raise_with_stopped_traceback(ValueError, "called with '" + var_name + "' being more than maximum value of " + str(max_value) + ".")
129
+ return value
130
+
131
+
132
+ def get_validated_float(self, var_name, min_value=None, max_value=None, strict=False, *, default=None, return_limits=False):
133
+ """Returns a validated float value or raises exception. Optional checking for limits (min_value, max_value) or in strict
134
+ mode (not allowing string representation of an float). Specifying an float value with default=[float] or setting
135
+ return_limits=True will prohibit an exception being raised and the default or exceeded limit value is returned."""
136
+
137
+ reset_traceback()
138
+ if default is not None and not isinstance(default, float):
139
+ raise_with_stopped_traceback(TypeError, "called with 'default' not being a float.")
140
+
141
+ value = get_value_for_var_name(var_name)
142
+ # might be string representation
143
+ if isinstance(value, str):
144
+ if strict:
145
+ if default is not None:
146
+ return default
147
+ raise_with_stopped_traceback(TypeError, "called with '" + var_name + "' not being a string.")
148
+ else:
149
+ sValue = value.strip()
150
+ period_pos = sValue.find(".")
151
+ if period_pos > -1:
152
+ # trim trailing zeros
153
+ sPos = len(sValue) - 1
154
+ while sPos > period_pos + 2:
155
+ if sValue[sPos] == "0":
156
+ sPos -= 1
157
+ else:
158
+ period_pos = len(sValue)
159
+ sValue = sValue[:sPos+1]
160
+ else:
161
+ sValue += ".0"
162
+ try:
163
+ value = float(sValue)
164
+ if str(value) != sValue:
165
+ value = None
166
+ except Exception as e:
167
+ value = None
168
+ elif isinstance(value, int):
169
+ # accepting int as float
170
+ value = float(value)
171
+ # check for float
172
+ if not isinstance(value, float):
173
+ if default is not None:
174
+ return default
175
+ raise_with_stopped_traceback(TypeError, "called with '" + var_name + "' not being a float or a string representation of a float.")
176
+ if min_value is not None and value < min_value:
177
+ if return_limits:
178
+ return min_value
179
+ if default is not None:
180
+ return default
181
+ raise_with_stopped_traceback(ValueError, "called with '" + var_name + "' being less than minimum value of " + str(min_value) + ".")
182
+ if max_value is not None and value > max_value:
183
+ if return_limits:
184
+ return max_value
185
+ if default is not None:
186
+ return default
187
+ raise_with_stopped_traceback(ValueError, "called with '" + var_name + "' being more than maximum value of " + str(max_value) + ".")
188
+ return value
189
+
190
+
191
+
192
+ def get_validated_str(self, var_name, min_length=1, strict=False, *, default=None):
193
+ """Returns a validated string value or raises exception. Optional checking in strict mode (not allowing non-string
194
+ values that can be converted to string). Specifying an string value with default=[string] will prohibit an
195
+ exception being raised and the default being returned."""
196
+
197
+ reset_traceback()
198
+ if default is not None and not isinstance(default, str):
199
+ raise_with_stopped_traceback(TypeError, "called with 'default' not being a string.")
200
+
201
+ value = get_value_for_var_name(var_name)
202
+ if not isinstance(value, str):
203
+ if strict:
204
+ if default is not None:
205
+ return default
206
+ raise_with_stopped_traceback(TypeError, "called with '" + var_name + "' not being a string.")
207
+ else:
208
+ try:
209
+ value = str(value)
210
+ except:
211
+ if default is not None:
212
+ return default
213
+ raise_with_stopped_traceback(TypeError, "called with '" + var_name + "' not being convertable to a string.")
214
+
215
+ if len(value) < min_length:
216
+ if default is not None:
217
+ return default
218
+ raise_with_stopped_traceback(ValueError, "called with length of '" + var_name + "' being less than " + str(min_length) + " characters.")
219
+ return value
220
+
@@ -0,0 +1,6 @@
1
+ # limit the exported strings for 'import *' usage
2
+ __all__ = [
3
+ "ArgValidator"
4
+ ]
5
+
6
+ from .ArgValidator import ArgValidator
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: spArgValidatorPy
3
+ Version: 1.0.1
4
+ Summary: A Python package for validating function arguments and either raising an exception or returning the validated value.
5
+ Project-URL: Homepage, https://github.com/krokoreit/spArgValidatorPy
6
+ Project-URL: Source Code, https://github.com/krokoreit/spArgValidatorPy
7
+ Author-email: krokoreit <krokoreit@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: argument validation,function arguments,valid float,valid integer,valid string,validator
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+
16
+ # spArgValidatorPy
17
+
18
+ [![PyPI - Version](https://img.shields.io/pypi/v/spArgValidatorPy.svg)](https://pypi.org/project/spArgValidatorPy)
19
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/spArgValidatorPy.svg)](https://pypi.org/project/spArgValidatorPy)
20
+
21
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
22
+
23
+
24
+ This package provides a Python module for validating function arguments. Depending on the outcome, it either raises an exception or returns the validated value.
25
+
26
+ If a numeric argument is provided as a string representation (e.g. "100" or "3.24"), it will be converted and returned as a valid int or float, unless validation is performed in strict mode. Numeric arguments can also be checked against minimum and/or maximum limits.
27
+
28
+ String arguments are considered valid if they can be converted to a string (e.g. 123 becomes "123"), unless validation is done in strict mode, which only accepts values of type str. By default, empty strings cause an exception, but this can be disabled by allowing a minimum length of 0.
29
+
30
+ All validation functions support an optional default argument. If provided, this value is returned instead of raising an exception when validation fails. This simplifies code by removing the need for a separate try–except block to set fallback values. The default must be passed as a keyword argument (default=value) and must match the expected type (str, int, or float).
31
+
32
+ For numeric validations, you can also enable the return_limits=True option to return the defined minimum or maximum value instead of raising an exception.
33
+
34
+ For more details, see the API reference below and the examples in examples/example01.py, which includes over 20 usage demonstrations.
35
+
36
+ Enjoy
37
+
38
+ &emsp;krokoreit
39
+ &emsp;&emsp;&emsp;<img src="![assets/krokoreit-01.svg](https://github.com/krokoreit/spArgValidatorPy/blob/main/assets/krokoreit-01.svg)" width="140"/>
40
+
41
+
42
+ ## Installation
43
+
44
+ ```console
45
+ pip install spArgValidatorPy
46
+ ```
47
+
48
+
49
+ ## Usage & API
50
+
51
+ ### ArgValidator Class
52
+ Import module and instantiate an ArgValidator object:
53
+ ```py
54
+ from spArgValidatorPy import ArgValidator
55
+
56
+ av = ArgValidator()
57
+ ```
58
+
59
+ Argument validation is then as simple as
60
+ ```py
61
+ def my_function(str_arg, int_arg, float_arg):
62
+ str_arg = av.get_validated_str("str_arg")
63
+ int_arg = av.get_validated_int("int_arg")
64
+ float_arg = av.get_validated_float("float_arg")
65
+ ....
66
+ ```
67
+ Note that the name of the argument is passed to the validation function and not the value.
68
+ After successful validation (no exception raised), these variables can be safely used as str, int and float. For more complex validation with the use of strict mode, minimum or maximum values allowed or defaults, see the validation functions below.
69
+
70
+
71
+ </br>
72
+
73
+ ### API
74
+
75
+ #### Methods
76
+ * [get_validated_int()](#get_validated_int-method)
77
+ * [get_validated_float()](#get_validated_float-method)
78
+ * [get_validated_str()](#get_validated_str-method)
79
+ </br>
80
+ </br>
81
+
82
+
83
+ #### get_validated_int() Method
84
+ ```py
85
+ get_validated_int(var_name, min_value, max_value, strict, default=int_value, return_limits=boolean_value)
86
+ ```
87
+ Arguments:
88
+ - var_name
89
+ The name of the argument being validated.
90
+ - min_value
91
+ Optional lower limit to validate var_name's value against.
92
+ - max_value
93
+ Optional upper limit to validate var_name's value against.
94
+ - strict
95
+ Optional boolean argument to allow only integers as var_name's value, when set to True. The default is validation in non-strict mode, which allows string representations of an integer (e.g. "220").
96
+ - default=int_value
97
+ Optional keyword argument for an integer default value. When set, it avoids an exception being raised in case var_name's value fails validation and this default value is returned instead.
98
+ - return_limits=boolean_value
99
+ Optional keyword argument to avoid an exception being raised for values outside the limits.
100
+ When set to True and with either min_value or max_value being exceeded, this limit value is returned as validated value.
101
+
102
+ Returns the validated integer value or with the default or return_limits option used, one of these values instead of an exception raised.
103
+
104
+ <div style="text-align: right"><a href="#methods">&#8679; back up to list of methods</a></div>
105
+
106
+ </br>
107
+
108
+ #### get_validated_float() Method
109
+ ```py
110
+ get_validated_float(var_name, min_value, max_value, strict, default=float_value, return_limits=boolean_value)
111
+ ```
112
+ Arguments:
113
+ - var_name
114
+ The name of the argument being validated.
115
+ - min_value
116
+ Optional lower limit to validate var_name's value against.
117
+ - max_value
118
+ Optional upper limit to validate var_name's value against.
119
+ - strict
120
+ Optional boolean argument to allow only a float as var_name's value, when set to True. The default is validation in non-strict mode, which allows string representations of a float (e.g. "1.99").
121
+ - default=float_value
122
+ Optional keyword argument for a float default value. When set, it avoids an exception being raised in case var_name's value fails validation and this default value is returned instead.
123
+ - return_limits=boolean_value
124
+ Optional keyword argument to avoid an exception being raised for values outside the limits.
125
+ When set to True and with either min_value or max_value being exceeded, this limit value is returned as validated value.
126
+
127
+ Returns the validated float value or with the default or return_limits option used, one of these values instead of an exception raised.
128
+
129
+
130
+ <div style="text-align: right"><a href="#methods">&#8679; back up to list of methods</a></div>
131
+
132
+ </br>
133
+
134
+ #### get_validated_str() Method
135
+ ```py
136
+ get_validated_str(var_name, min_length, strict, default=str_value)
137
+ ```
138
+ - var_name
139
+ The name of the argument being validated.
140
+ - min_length
141
+ The minimum length required for a valid string. By default thi sis set to 1, meaning that empty strings will throw an exception. This can be set to 0 to allow empty strings or to any other length, against which you want to validate.
142
+ - strict
143
+ Optional boolean argument to allow only a string as var_name's value, when set to True. The default is validation in non-strict mode, which allows any value, which can be converted into a string.
144
+ - default=str_value
145
+ Optional keyword argument for a string default value. When set, it avoids an exception being raised in case var_name's value fails validation and this default value is returned instead.
146
+
147
+ Returns the validated string value or with the default option used, this value instead of an exception raised.
148
+
149
+ <div style="text-align: right"><a href="#methods">&#8679; back up to list of methods</a></div>
150
+
151
+ </br>
152
+
153
+ ## License
154
+ MIT license
155
+ Copyright &copy; 2025 by krokoreit
@@ -0,0 +1,6 @@
1
+ spArgValidatorPy/ArgValidator.py,sha256=JCecoyrZp9Krnme3UaVIrQGbIl94PMT5bWZ7xy-AedY,10662
2
+ spArgValidatorPy/__init__.py,sha256=MsbSdo-oz6o-PhLXcomI11bBZkU5bDNiB-9hmreuhl8,129
3
+ spargvalidatorpy-1.0.1.dist-info/METADATA,sha256=4dw1Mf_XxaIYlyVH-3Rib0H0rxa8kkPQ6tb-t4qWdgA,7347
4
+ spargvalidatorpy-1.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ spargvalidatorpy-1.0.1.dist-info/licenses/LICENSE,sha256=OGLCoSaPB4W5LyOH3IQDWolNTYJCyW2UgpllcHnEm3c,1109
6
+ spargvalidatorpy-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 krokoreit (krokoreit@gmail.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.