pyvarcheck 0.0.2__tar.gz → 0.0.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyvarcheck
3
- Version: 0.0.2
3
+ Version: 0.0.4
4
4
  Summary: Easy, high-level var testing for python with auto-conversion features
5
5
  Author: Benjamin Winter
6
6
  License: MIT
@@ -40,12 +40,12 @@ Everything's neatly documented in there.
40
40
 
41
41
  - Whenever a check succeeds, every function of *pyvarcheck* returns True. When parameter [convert] is set True, it converts the input item properly and returns it.
42
42
  - Whenever a check fails, every function of *pyvarcheck* raises Exception type `pyvarcheck.varcheck_exc`.
43
- - On the occasion that there's a programmatic error in any *pyvarcheck* function (sorry, my bad), *pyvarcheck* raises the original exception to the caller. Feel free report such occasions.
43
+ - On the occasion that there's a programmatic error in any *pyvarcheck* function (sorry, my bad), *pyvarcheck* raises the original exception to the caller. Feel free to report such occasions.
44
44
 
45
45
  ## Basics
46
46
  **Compatibility** in short: any platform on Python 3.10+. OS-independent.
47
47
  **Status:** *public beta*. Should work without issues, waiting for community response before releasing final v1.
48
- **Built** on W11 25H2 with python 3.14.2, pip 26.2.1, build 1.5.0, twine 7.0.0. Standard settings.
48
+ **Built** on W11 25H2 with python 3.15.0, pip 26.2.2, build 1.6.1, twine 7.0.0. Standard settings.
49
49
 
50
50
  ## Build from source
51
51
  The library is built witout any special options - as per the pypi manual. It uses `setuptools` (`setup.py`) and not the toml file.
@@ -19,12 +19,12 @@ Everything's neatly documented in there.
19
19
 
20
20
  - Whenever a check succeeds, every function of *pyvarcheck* returns True. When parameter [convert] is set True, it converts the input item properly and returns it.
21
21
  - Whenever a check fails, every function of *pyvarcheck* raises Exception type `pyvarcheck.varcheck_exc`.
22
- - On the occasion that there's a programmatic error in any *pyvarcheck* function (sorry, my bad), *pyvarcheck* raises the original exception to the caller. Feel free report such occasions.
22
+ - On the occasion that there's a programmatic error in any *pyvarcheck* function (sorry, my bad), *pyvarcheck* raises the original exception to the caller. Feel free to report such occasions.
23
23
 
24
24
  ## Basics
25
25
  **Compatibility** in short: any platform on Python 3.10+. OS-independent.
26
26
  **Status:** *public beta*. Should work without issues, waiting for community response before releasing final v1.
27
- **Built** on W11 25H2 with python 3.14.2, pip 26.2.1, build 1.5.0, twine 7.0.0. Standard settings.
27
+ **Built** on W11 25H2 with python 3.15.0, pip 26.2.2, build 1.6.1, twine 7.0.0. Standard settings.
28
28
 
29
29
  ## Build from source
30
30
  The library is built witout any special options - as per the pypi manual. It uses `setuptools` (`setup.py`) and not the toml file.
@@ -13,7 +13,7 @@ long_description = (parent_dir / "README.md").read_text(encoding="utf-8")
13
13
 
14
14
  setuptools.setup (
15
15
  name = "pyvarcheck",
16
- version = '0.0.2',
16
+ version = '0.0.4',
17
17
  author = "Benjamin Winter",
18
18
  license= "MIT",
19
19
  description = "Easy, high-level var testing for python with auto-conversion features",
@@ -0,0 +1,232 @@
1
+ #Copyright (c) 2026 Benjamin Winter
2
+ #This file is part of pyvarcheck which is released under the MIT License.
3
+ #See file LICENSE or go to https://github.com/core2000-eU/pyvarcheck for full license details.
4
+
5
+ #DESCRIPTION
6
+ #Easy, high-level var testing for python with auto-conversion features.
7
+
8
+ #imports
9
+ import inspect
10
+ import uuid
11
+ import ipaddress
12
+ import re
13
+ import pathlib
14
+
15
+ #global vars
16
+ precomp_regex_1 = re.compile(r"^[a-zA-Z0-9_.]+$") #used often
17
+ precomp_regex_2 = re.compile(r"^[a-zA-Z0-9_\-.]+$") #used often
18
+ gen_char_limit = 1024**2 #diced; just to have some theoretical yet practical limit
19
+ shorten_remove_1_byt = [b"a",b"e",b"i",b"o",b"u",b" "]
20
+ shorten_remove_1_str = ["a","e","i","o","u"," "]
21
+
22
+ #exception types
23
+ class pyvarcheck_exc(Exception):
24
+ def __init__(self,error): super().__init__(error); self.error=error; self.is_exception_from_lib_pyvarcheck=True;
25
+ def __str__(self): return f"{self.error}"
26
+
27
+ #frontend user-facing functions
28
+ def utf8(obj_in,convert=False,exc_prepend="",exc_append=""):
29
+ try:
30
+ try:
31
+ helpers.raise_unknown_input_type(obj_in,[bytes,str])
32
+ if isinstance(obj_in, str): _=obj_in.encode("utf-8",errors="strict")
33
+ elif isinstance(obj_in, bytes): _=obj_in.decode("utf-8",errors="strict").encode("utf-8",errors="strict")
34
+ except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}cannot encode in UTF-8. encode('utf-8', errors='strict') failed with exception {e.__repr__()}{exc_append}")
35
+ if(convert): return obj_in
36
+ return True
37
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
38
+ def uuid4(obj_in,convert=False,exc_prepend="",exc_append=""):
39
+ try:
40
+ try:
41
+ helpers.raise_unknown_input_type(obj_in,[bytes,str])
42
+ if isinstance(obj_in, bytes): _=uuid.UUID(bytes=obj_in,version=4)
43
+ elif isinstance(obj_in, str): _=uuid.UUID(obj_in,version=4)
44
+ except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}cannot convert to UUID. Operation failed with exception {e.__repr__()}{exc_append}")
45
+ if(convert):
46
+ if isinstance(obj_in, bytes): return uuid.UUID(bytes=obj_in,version=4)
47
+ elif isinstance(obj_in, str): return uuid.UUID(obj_in,version=4)
48
+ return True
49
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
50
+ def arg_name(obj_in,maxlen=128,reservedchars=[],convert=False,exc_prepend="",exc_append=""):
51
+ """
52
+ brief check whether [obj_in] fulfills requirements as argument name: Latin letters, numbers, and only some special chars allowed.
53
+ param [obj_in] STR|BYTES as input
54
+ param [maxlen] INT the max. length of [obj_in]; NOTE: compares against python's len() function, which specifies codepoints for STR and octets for BYTES, not human-readable chars.
55
+ param [reservedchars] LIST(STR|BYTES) a list of STR|BYTES which [obj_in] must not contain
56
+ param [convert] BOOL if False, function returns True; if True, function returns [obj_in]
57
+ param [exc_prepend] STR text to prepend when raising an exception
58
+ param [exc_append] STR text to append when raising an exception
59
+ RAISES pyvarcheck.pyvarcheck_exc when conditions not met
60
+ any other exception in all other cases, e.g. you provided wrong input data or library-internal exception occured
61
+ """
62
+ try:
63
+ _=helpers.check_utf8_maxlen_reservedchars(obj_in=obj_in,maxlen=maxlen,reservedchars=reservedchars)
64
+ _=helpers.do_regex_match_and_find_err_pos(regex_match=precomp_regex_2,obj_in=obj_in)
65
+ if(convert): return obj_in
66
+ return True
67
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
68
+ def generic_name(obj_in,maxlen=128,reservedchars=[],check_printable=True,ignore_newlinesTabs=False,convert=False,exc_prepend="",exc_append=""):
69
+ """
70
+ brief check whether [obj_in] fulfills requirements as a generic name: UTF-8, special chars, numbers, all alphabet letters principally allowed.
71
+ param [obj_in] STR|BYTES as input
72
+ param [maxlen] INT the max. length of [obj_in]; NOTE: compares against python's len() function, which specifies codepoints for STR and octets for BYTES, not human-readable chars.
73
+ param [reservedchars] LIST(STR|BYTES) a list of STR|BYTES which [obj_in] must not contain
74
+ param [check_printable] BOOL if True, check [obj_in] against python's isprintable() which smartly allows characters of all alphabets, numbers etc. but no "hidden" / control chars / special codepoints
75
+ param [ignore_newlinesTabs] BOOL if True, \r,\n, and \t are excluded from [check_printable] check
76
+ param [convert] BOOL if False, function returns True; if True, function returns [obj_in]
77
+ param [exc_prepend] STR text to prepend when raising an exception
78
+ param [exc_append] STR text to append when raising an exception
79
+ RAISES pyvarcheck.pyvarcheck_exc when conditions not met
80
+ any other exception in all other cases, e.g. you provided wrong input data or library-internal exception occured
81
+ """
82
+ try:
83
+ _=helpers.check_utf8_maxlen_reservedchars(obj_in=obj_in,maxlen=maxlen,reservedchars=reservedchars)
84
+ if(check_printable): _=helpers.check_is_printable(obj_in=obj_in,ignore_newlinesTabs=ignore_newlinesTabs)
85
+ if(convert): return obj_in
86
+ return True
87
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
88
+ def hostname(obj_in,maxlen=64,reservedchars=[],convert=False,exc_prepend="",exc_append=""):
89
+ try:
90
+ _=helpers.check_utf8_maxlen_reservedchars(obj_in=obj_in,maxlen=maxlen,reservedchars=reservedchars)
91
+ _=helpers.do_regex_match_and_find_err_pos(regex_match=precomp_regex_2,obj_in=obj_in)
92
+ if(convert): return obj_in
93
+ return True
94
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
95
+ def generic_description(obj_in,maxlen=gen_char_limit,reservedchars=[],re_match=r"",check_printable=True,ignore_newlinesTabs=False,convert=False,exc_prepend="",exc_append=""):
96
+ try:
97
+ _=helpers.check_utf8_maxlen_reservedchars(obj_in=obj_in,maxlen=maxlen,reservedchars=reservedchars)
98
+ if(check_printable): _=helpers.check_is_printable(obj_in=obj_in,ignore_newlinesTabs=ignore_newlinesTabs)
99
+ if(re_match!=r""): _=helpers.do_regex_match_and_find_err_pos(regex_match=re_match,obj_in=obj_in) #regex match only when given, it's quite slow
100
+ if(convert): return obj_in
101
+ return True
102
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
103
+ def ipv4_addr(obj_in,convert=False,exc_prepend="",exc_append=""):
104
+ try:
105
+ #convert bytes->str if needed
106
+ if isinstance(obj_in, bytes): obj_in=utf8(obj_in=obj_in,convert=True,exc_prepend=exc_prepend,exc_append=exc_append).decode("utf-8",errors="ignore")
107
+ #conver to IP
108
+ try: _=ipaddress.IPv4Address(obj_in)
109
+ except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}not an IPv4 address. ipaddress.IPv4Address(*) failed with exception {e.__repr__()}{exc_append}")
110
+ if(convert): return ipaddress.IPv4Address(obj_in)
111
+ return True
112
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
113
+ def ipv6_addr(obj_in,convert=False,exc_prepend="",exc_append=""):
114
+ try:
115
+ #convert bytes->str if needed
116
+ if isinstance(obj_in, bytes): obj_in=utf8(obj_in=obj_in,convert=True,exc_prepend=exc_prepend,exc_append=exc_append).decode("utf-8",errors="ignore")
117
+ #conver to IP
118
+ try: _=ipaddress.IPv6Address(obj_in)
119
+ except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}not an IPv6 address. ipaddress.IPv6Address(*) failed with exception {e.__repr__()}{exc_append}")
120
+ if(convert): return ipaddress.IPv6Address(obj_in)
121
+ return True
122
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
123
+ def tcpip_port(obj_in,convert=False,exc_prepend="",exc_append=""):
124
+ try:
125
+ helpers.raise_unknown_input_type(obj_in,[int,str,bytes])
126
+ try: obj_in_tmp=int(obj_in)
127
+ except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}expected datatype compatible with (convertible to) [int] but got [{type(obj_in).__qualname__}({obj_in})]{exc_append}")
128
+ if( not obj_in_tmp > 0 ) or ( not obj_in_tmp <= 65535 ): raise pyvarcheck_exc(f"{exc_prepend}expected TCP/IP Port number in range [1-65535]; to make it clear: (0 ≤ x ≤ 65535, x ∈ ℤ){exc_append}")
129
+ if(convert): return int(obj_in)
130
+ return True
131
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
132
+ def int_minmax(obj_in,value_min,value_max,convert=False,exc_prepend="",exc_append=""):
133
+ try:
134
+ helpers.raise_unknown_input_type(obj_in,[int,str,bytes])
135
+ try: obj_in_tmp=int(obj_in)
136
+ except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}expected datatype compatible with (convertible to) [int] but got [{type(obj_in).__qualname__}({obj_in})]{exc_append}")
137
+ if( not obj_in_tmp >= value_min ) or ( not obj_in_tmp <= value_max ): raise pyvarcheck_exc(f"{exc_prepend}expected integer value between (incl.) [{value_min}] and (incl.) [{value_max}]; to make it clear: ({value_min} ≤ x ≤ {value_max}, x ∈ ℤ){exc_append}")
138
+ if(convert): return int(obj_in)
139
+ return True
140
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
141
+ def bool_compatible(obj_in,convert=False,exc_prepend="",exc_append=""):
142
+ try:
143
+ helpers.raise_unknown_input_type(obj_in,[str,bytes,int,bool])
144
+ dataout=None
145
+ if isinstance(obj_in,int) or isinstance(obj_in,bool):
146
+ _=int_minmax(obj_in=obj_in,value_min=0,value_max=1,exc_prepend=exc_prepend,exc_append=exc_append)
147
+ dataout=bool(obj_in)
148
+ elif isinstance(obj_in,str) or isinstance(obj_in,bytes):
149
+ _=helpers.check_utf8_maxlen_reservedchars(obj_in=obj_in,maxlen=5,reservedchars=[])
150
+ obj_in_tmp=obj_in.lower()
151
+ if isinstance(obj_in_tmp,bytes): obj_in_tmp=obj_in_tmp.decode("utf-8",errors="ignore")
152
+ match obj_in_tmp:
153
+ case "true": dataout=True
154
+ case "false": dataout=False
155
+ case "1": dataout=True
156
+ case "0": dataout=False
157
+ case _: raise pyvarcheck_exc(f"{exc_prepend}expected value convertable to bool. Either integer [0|1] or str ['true'|'false'] but got [{type(obj_in).__qualname__}({obj_in})]{exc_append}")
158
+ if(dataout==None): raise Exception(f"internal exception: unexpected value [None] for var [dataout]. Please report. For debugging: [obj_in]={obj_in}, [exc_prepend]={exc_prepend}, [exc_append]={exc_append}, [convert]={convert}; end of debug")
159
+ if(convert): return bool(dataout)
160
+ return True
161
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
162
+ def shorten(obj_in,maxlen=gen_char_limit,reservedchars=[],exc_prepend="",exc_append=""):
163
+ """
164
+ brief shorten [obj_in] smartly; only works for latin alphabet chars
165
+ param [obj_in] STR|BYTES as input
166
+ param [maxlen] INT the max. length of the returned object; NOTE: compares against python's len() function, which specifies codepoints for STR and octets for BYTES, not human-readable chars.
167
+ param [reservedchars] LIST(STR|BYTES) a list of STR|BYTES which output must not contain
168
+ param [exc_prepend] STR text to prepend when raising an exception
169
+ param [exc_append] STR text to append when raising an exception
170
+ """
171
+ try:
172
+ helpers.raise_unknown_input_type(obj_in,[str,bytes])
173
+ if isinstance(obj_in,bytes):
174
+ for letter in shorten_remove_1_byt: obj_in=obj_in.replace( letter.lower(),b"" ).replace( letter.upper(),b"" )
175
+ for letter in reservedchars:
176
+ if isinstance(letter,str): letter=letter.encode("utf-8",errors="ignore")
177
+ obj_in=obj_in.replace( letter.lower(),b"" ).replace( letter.upper(),b"" )
178
+ return obj_in[:maxlen+1]
179
+ elif isinstance(obj_in,str):
180
+ for letter in shorten_remove_1_str: obj_in=obj_in.replace( letter.lower(),"" ).replace( letter.upper(),"" )
181
+ for letter in reservedchars:
182
+ if isinstance(letter,bytes): letter=letter.decode("utf-8",errors="ignore")
183
+ obj_in=obj_in.replace( letter.lower(),"" ).replace( letter.upper(),"" )
184
+ return obj_in[:maxlen+1]
185
+ except Exception as e: helpers.raise_exc_properly(exc=e,funcname=inspect.currentframe().f_code.co_name,exc_prepend=exc_prepend,exc_append=exc_append)
186
+
187
+ #backend functions
188
+ class helpers:
189
+ def check_utf8_maxlen_reservedchars(obj_in,maxlen,reservedchars):
190
+ _=utf8(obj_in=obj_in,exc_prepend="",exc_append="")
191
+ if( len(obj_in) > maxlen ): raise pyvarcheck_exc(f"max length is [{maxlen}] but actual length is [{len(obj_in)}]")
192
+ for reservedchar in reservedchars:
193
+ if( isinstance(obj_in,str) and isinstance(reservedchar,bytes) ): reservedchar=reservedchar.decode("utf-8",errors="ignore")
194
+ elif( isinstance(obj_in,bytes) and isinstance(reservedchar,str) ): reservedchar=reservedchar.encode("utf-8",errors="ignore")
195
+ if( reservedchar in obj_in ):
196
+ _pos = obj_in.find(reservedchar)
197
+ raise pyvarcheck_exc(f"position [{_pos}] contains char that is in 'reservedchars' list. position is 0-based. char in question is '{reservedchar}', 'reservedchars' list is {reservedchars}")
198
+ return True
199
+ def do_regex_match_and_find_err_pos(regex_match,obj_in):
200
+ helpers.raise_unknown_input_type(obj_in,[bytes,str])
201
+ if isinstance(obj_in, bytes): obj_in=utf8(obj_in=obj_in,convert=True,exc_prepend="",exc_append="").decode("utf-8",errors="ignore")
202
+ if( not bool(re.match(regex_match, obj_in)) ):
203
+ for i, char in enumerate(obj_in):
204
+ if( not bool(re.match(regex_match, char)) ):
205
+ raise pyvarcheck_exc(f"contains invalid char (byte value 0x{char.encode("utf-8",errors="ignore").hex()}) at position [{i}]. re.match(r'{regex_match}') failed. position is 0-based")
206
+ return True;
207
+ def check_is_printable(obj_in,ignore_newlinesTabs):
208
+ obj_in_tmp=obj_in
209
+ if isinstance(obj_in_tmp, bytes): obj_in_tmp=utf8(obj_in=obj_in_tmp,convert=True,exc_prepend="",exc_append="").decode("utf-8",errors="ignore")
210
+ if(ignore_newlinesTabs): obj_in_tmp=obj_in_tmp.replace("\r","").replace("\n","").replace("\t","")
211
+ if not obj_in_tmp.isprintable(): raise pyvarcheck_exc(f"contains non-printable codepoints, not allowed")
212
+ return obj_in
213
+ def raise_exc_properly(exc,funcname,exc_prepend="",exc_append=""):
214
+ if isinstance(exc,pyvarcheck_exc):
215
+ raise type(exc)(f"{exc_prepend}{type(exc).__qualname__}('{exc}'){exc_append}") from exc #raise the same orig. exception type with prepended and appended message
216
+ else:
217
+ tb = exc.__traceback__
218
+ while tb.tb_next:
219
+ tb = tb.tb_next
220
+ line_number = tb.tb_lineno
221
+ absolute_path = pathlib.Path(tb.tb_frame.f_code.co_filename).resolve()
222
+ addl_file_info=f" at file {absolute_path}, line {line_number}"
223
+ raise type(exc)(f"{exc_prepend}lib pyvarcheck: function {funcname}() raised internal Exception {type(exc).__qualname__}('{exc}') {addl_file_info}{exc_append}") from exc #raise the same orig. exception type with prepended and appended message
224
+ def raise_unknown_input_type(obj_in,allowed=[]):
225
+ for type_ in allowed:
226
+ if isinstance(obj_in,type_): break;
227
+ else:
228
+ #prepare
229
+ type_objin=type(obj_in).__name__
230
+ type_allowed=[i.__name__ for i in allowed]
231
+ #raise
232
+ raise pyvarcheck_exc(f"unknown input type '{type_objin}'. Allowed types are {type_allowed}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyvarcheck
3
- Version: 0.0.2
3
+ Version: 0.0.4
4
4
  Summary: Easy, high-level var testing for python with auto-conversion features
5
5
  Author: Benjamin Winter
6
6
  License: MIT
@@ -40,12 +40,12 @@ Everything's neatly documented in there.
40
40
 
41
41
  - Whenever a check succeeds, every function of *pyvarcheck* returns True. When parameter [convert] is set True, it converts the input item properly and returns it.
42
42
  - Whenever a check fails, every function of *pyvarcheck* raises Exception type `pyvarcheck.varcheck_exc`.
43
- - On the occasion that there's a programmatic error in any *pyvarcheck* function (sorry, my bad), *pyvarcheck* raises the original exception to the caller. Feel free report such occasions.
43
+ - On the occasion that there's a programmatic error in any *pyvarcheck* function (sorry, my bad), *pyvarcheck* raises the original exception to the caller. Feel free to report such occasions.
44
44
 
45
45
  ## Basics
46
46
  **Compatibility** in short: any platform on Python 3.10+. OS-independent.
47
47
  **Status:** *public beta*. Should work without issues, waiting for community response before releasing final v1.
48
- **Built** on W11 25H2 with python 3.14.2, pip 26.2.1, build 1.5.0, twine 7.0.0. Standard settings.
48
+ **Built** on W11 25H2 with python 3.15.0, pip 26.2.2, build 1.6.1, twine 7.0.0. Standard settings.
49
49
 
50
50
  ## Build from source
51
51
  The library is built witout any special options - as per the pypi manual. It uses `setuptools` (`setup.py`) and not the toml file.
@@ -1,147 +0,0 @@
1
- #Copyright (c) 2026 Benjamin Winter
2
- #This file is part of pyvarcheck which is released under the MIT License.
3
- #See file LICENSE or go to https://github.com/core2000-eU/pyvarcheck for full license details.
4
-
5
- #DESCRIPTION
6
- #Easy, high-level var testing for python with auto-conversion features.
7
-
8
- #imports
9
- import inspect
10
- import uuid
11
- import ipaddress
12
- import re
13
-
14
- #global vars
15
- precomp_regex_1 = re.compile(r"^[a-zA-Z0-9_.]+$") #used often
16
- precomp_regex_2 = re.compile(r"^[a-zA-Z0-9_\-.]+$") #used often
17
- gen_char_limit = 1024**2 #diced; just to have some theoretical yet practical limit
18
-
19
- #exception types
20
- class pyvarcheck_exc(Exception):
21
- def __init__(self,error): super().__init__(error); self.error=error; self.is_exception_from_lib_pyvarcheck=True;
22
- def __str__(self): return f"{self.error}"
23
-
24
- #frontend user-facing functions
25
- def str_utf8(obj_in,convert=False,exc_prepend="",exc_append=""):
26
- try:
27
- try: _=obj_in.encode("utf-8", errors="strict")
28
- except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}cannot encode in UTF-8. *.encode('utf-8', errors='strict') failed with exception {e.__repr__()}{exc_append}")
29
- if(convert): return str(obj_in)
30
- return True
31
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
32
- def uuid4(obj_in,convert=False,exc_prepend="",exc_append=""):
33
- try:
34
- try: _=uuid.UUID(obj_in,version=4)
35
- except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}cannot convert to UUID. Operation failed with exception {e.__repr__()}{exc_append}")
36
- if(convert): return uuid.UUID(obj_in,version=4)
37
- return True
38
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
39
- def arg_name(obj_in,maxlen=128,reservedchars=[],convert=False,exc_prepend="",exc_append=""):
40
- try:
41
- _=helpers.check_utf8_maxlen_reservedchars(obj_in,gen_char_limit,reservedchars,exc_prepend,exc_append)
42
- _=helpers.do_regex_match_and_find_err_pos(precomp_regex_2,obj_in,exc_prepend,exc_append)
43
- if(convert): return str(obj_in)
44
- return True
45
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
46
- def generic_name(obj_in,maxlen=128,reservedchars=[],convert=False,exc_prepend="",exc_append=""):
47
- try:
48
- _=helpers.check_utf8_maxlen_reservedchars(obj_in,maxlen,reservedchars,exc_prepend,exc_append)
49
- if(convert): return str(obj_in)
50
- return True
51
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
52
- def hostname(obj_in,maxlen=64,reservedchars=[],convert=False,exc_prepend="",exc_append=""):
53
- try:
54
- _=helpers.check_utf8_maxlen_reservedchars(obj_in,maxlen,reservedchars,exc_prepend,exc_append)
55
- _=helpers.do_regex_match_and_find_err_pos(precomp_regex_2,obj_in,exc_prepend,exc_append)
56
- if(convert): return str(obj_in)
57
- return True
58
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
59
- def generic_description(obj_in,maxlen=gen_char_limit,reservedchars=[],re_match=r"",convert=False,exc_prepend="",exc_append=""):
60
- try:
61
- _=helpers.check_utf8_maxlen_reservedchars(obj_in,maxlen,reservedchars,exc_prepend,exc_append)
62
- if(re_match!=r""): _=helpers.do_regex_match_and_find_err_pos(re_match,obj_in,exc_prepend,exc_append) #regex match only when given, it's quite slow
63
- if(convert): return str(obj_in)
64
- return True
65
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
66
- def ipv4_addr(obj_in,convert=False,exc_prepend="",exc_append=""):
67
- try:
68
- try: _=ipaddress.IPv4Address(obj_in)
69
- except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}not an IPv4 address. ipaddress.IPv4Address(*) failed with exception {e.__repr__()}{exc_append}")
70
- if(convert): return ipaddress.IPv4Address(obj_in)
71
- return True
72
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
73
- def ipv6_addr(obj_in,convert=False,exc_prepend="",exc_append=""):
74
- try:
75
- try: _=ipaddress.IPv6Address(obj_in)
76
- except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}not an IPv6 address. ipaddress.IPv6Address(*) failed with exception {e.__repr__()}{exc_append}")
77
- if(convert): return ipaddress.IPv6Address(obj_in)
78
- return True
79
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
80
- def tcpip_port(obj_in,convert=False,exc_prepend="",exc_append=""):
81
- try:
82
- try: obj_in_tmp=int(obj_in)
83
- except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}expected datatype compatible with (convertible to) [int] but got [{type(obj_in).__qualname__}({obj_in})]{exc_append}")
84
- if( not obj_in_tmp > 0 ) or ( not obj_in_tmp <= 65535 ): raise pyvarcheck_exc(f"{exc_prepend}expected TCP/IP Port number in range [1-65535]; to make it clear: (0 ≤ x ≤ 65535, x ∈ ℤ){exc_append}")
85
- if(convert): return int(obj_in)
86
- return True
87
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
88
- def int_minmax(obj_in,value_min,value_max,convert=False,exc_prepend="",exc_append=""):
89
- try:
90
- try: obj_in_tmp=int(obj_in)
91
- except Exception as e: raise pyvarcheck_exc(f"{exc_prepend}expected datatype compatible with (convertible to) [int] but got [{type(obj_in).__qualname__}({obj_in})]{exc_append}")
92
- if( not obj_in_tmp >= value_min ) or ( not obj_in_tmp <= value_max ): raise pyvarcheck_exc(f"{exc_prepend}expected integer value between (incl.) [{value_min}] and (incl.) [{value_max}]; to make it clear: ({value_min} ≤ x ≤ {value_max}, x ∈ ℤ){exc_append}")
93
- if(convert): return int(obj_in)
94
- return True
95
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
96
- def bool_compatible(obj_in,convert=False,exc_prepend="",exc_append=""):
97
- try:
98
- dataout=None
99
- if(isinstance(obj_in,int)):
100
- _=int_minmax(obj_in,0,1,exc_prepend,exc_append)
101
- dataout=bool(obj_in)
102
- elif(isinstance(obj_in,str)):
103
- _=helpers.check_utf8_maxlen_reservedchars(obj_in,5,[],exc_prepend,exc_append)
104
- obj_in_tmp = obj_in.lower()
105
- match obj_in_tmp:
106
- case "true": dataout=True
107
- case "false": dataout=False
108
- case "1": dataout=True
109
- case "0": dataout=False
110
- case _: raise pyvarcheck_exc(f"{exc_prepend}expected value convertable to bool. Either integer [0|1] or str ['true'|'false'] but got [{type(obj_in).__qualname__}({obj_in})]{exc_append}")
111
- else: raise pyvarcheck_exc(f"{exc_prepend}expected datatype either [int] or [str] but got [{type(obj_in).__qualname__}({obj_in})]{exc_append}")
112
- if(dataout==None): raise Exception(f"unexpected value [None] for var [dataout]. Please report. For debugging: [obj_in]={obj_in}, [exc_prepend]={exc_prepend}, [exc_append]={exc_append}, [convert]={convert}; end of debug")
113
- if(convert): return bool(dataout)
114
- return True
115
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
116
-
117
- #backend functions
118
- class helpers:
119
- def check_utf8_maxlen_reservedchars(obj_in,maxlen,reservedchars,exc_prepend,exc_append):
120
- try:
121
- pass; _=str_utf8(obj_in,exc_prepend,exc_append)
122
- if( len(obj_in) > maxlen ): raise pyvarcheck_exc(f"{exc_prepend}max length is [{maxlen}] but actual length is [{len(obj_in)}]{exc_append}")
123
- if( obj_in in reservedchars ): raise pyvarcheck_exc(f"{exc_prepend}contains string that is in 'reservedchars' list. 'reservedchars' list is {reservedchars}{exc_append}")
124
- for i,char in enumerate(obj_in):
125
- if( char in reservedchars ):
126
- char_hex = f"(byte value 0x{char.encode("utf-8",errors="ignore").hex()})";
127
- raise pyvarcheck_exc(f"{exc_prepend}contains char {char_hex} at position [{i}] that is in 'reservedchars' list. position is 0-based. 'reservedchars' list is {reservedchars}{exc_append}")
128
- return True
129
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
130
- def do_regex_match_and_find_err_pos(regex_match,obj_in,exc_prepend,exc_append):
131
- try:
132
- if( not bool(re.match(regex_match, obj_in)) ):
133
- for i, char in enumerate(obj_in):
134
- if( not bool(re.match(regex_match, char)) ):
135
- raise pyvarcheck_exc(f"{exc_prepend}contains invalid char (byte value 0x{char.encode("utf-8",errors="ignore").hex()}) at position [{i}]. re.match(r'{regex_match}') failed. position is 0-based.{exc_append}")
136
- return True;
137
- except Exception as e: helpers.raise_exc_properly(e,inspect.currentframe().f_code.co_name,exc_prepend,exc_append)
138
- def raise_exc_properly(exc,funcname,exc_prepend="",exc_append=""):
139
- if(isinstance(exc,pyvarcheck_exc)): raise exc
140
- else:
141
- tb = exc.__traceback__
142
- while tb.tb_next:
143
- tb = tb.tb_next
144
- line_number = tb.tb_lineno
145
- absolute_path = pathlib.Path(tb.tb_frame.f_code.co_filename).resolve()
146
- addl_file_info=f" at file {absolute_path}, line {line_number}"
147
- raise type(exc)(f"{exc_prepend}lib pyvarcheck: function {funcname}() raised internal Exception {exc} {addl_file_info}{exc_append}") from exc #raise the same orig. exception type with prepended message
File without changes
File without changes