abstract-utilities 0.2.2.436__py3-none-any.whl → 0.2.2.437__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.
Potentially problematic release.
This version of abstract-utilities might be problematic. Click here for more details.
- abstract_utilities/class_utils.py +39 -3
- abstract_utilities/dynimport.py +7 -15
- abstract_utilities/file_utils/imports/module_imports.py +1 -0
- abstract_utilities/log_utils.py +1 -1
- abstract_utilities/path_utils.py +42 -6
- abstract_utilities/read_write_utils.py +90 -154
- abstract_utilities/safe_utils.py +130 -0
- {abstract_utilities-0.2.2.436.dist-info → abstract_utilities-0.2.2.437.dist-info}/METADATA +1 -1
- {abstract_utilities-0.2.2.436.dist-info → abstract_utilities-0.2.2.437.dist-info}/RECORD +11 -10
- {abstract_utilities-0.2.2.436.dist-info → abstract_utilities-0.2.2.437.dist-info}/WHEEL +0 -0
- {abstract_utilities-0.2.2.436.dist-info → abstract_utilities-0.2.2.437.dist-info}/top_level.txt +0 -0
|
@@ -44,9 +44,9 @@ Dependencies:
|
|
|
44
44
|
Each function is furnished with its own docstring that elaborates on its purpose, expected inputs, and outputs.
|
|
45
45
|
|
|
46
46
|
"""
|
|
47
|
-
import inspect
|
|
48
|
-
import
|
|
49
|
-
|
|
47
|
+
import os,json,functools,inspect
|
|
48
|
+
from typing import *
|
|
49
|
+
|
|
50
50
|
def get_type_list() -> list:
|
|
51
51
|
"""Get a list of common Python types."""
|
|
52
52
|
return ['None','str','int','float','bool','list','tuple','set','dict','frozenset','bytearray','bytes','memoryview','range','enumerate','zip','filter','map','property','slice','super','type','Exception','object']
|
|
@@ -370,3 +370,39 @@ def get_class_inputs(cls, *args, **kwargs):
|
|
|
370
370
|
else:
|
|
371
371
|
values[field] = getattr(cls(), field)
|
|
372
372
|
return cls(**values)
|
|
373
|
+
def get_caller(i: Optional[int] = None) -> str:
|
|
374
|
+
"""
|
|
375
|
+
Return the filename of the calling frame.
|
|
376
|
+
|
|
377
|
+
Args:
|
|
378
|
+
i: Optional stack depth offset.
|
|
379
|
+
None = immediate caller (depth 1).
|
|
380
|
+
|
|
381
|
+
Returns:
|
|
382
|
+
Absolute path of the file for the stack frame.
|
|
383
|
+
"""
|
|
384
|
+
depth = 1 if i is None else int(i)
|
|
385
|
+
stack = inspect.stack()
|
|
386
|
+
if depth >= len(stack):
|
|
387
|
+
depth = len(stack) - 1
|
|
388
|
+
return stack[depth].filename
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def get_caller_path(i: Optional[int] = None) -> str:
|
|
392
|
+
"""
|
|
393
|
+
Return the absolute path of the caller's file.
|
|
394
|
+
"""
|
|
395
|
+
depth = 1 if i is None else int(i)
|
|
396
|
+
file_path = get_caller(depth + 1)
|
|
397
|
+
return os.path.realpath(file_path)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def get_caller_dir(i: Optional[int] = None) -> str:
|
|
401
|
+
"""
|
|
402
|
+
Return the absolute directory of the caller's file.
|
|
403
|
+
"""
|
|
404
|
+
depth = 1 if i is None else int(i)
|
|
405
|
+
abspath = get_caller_path(depth + 1)
|
|
406
|
+
return os.path.dirname(abspath)
|
|
407
|
+
|
|
408
|
+
|
abstract_utilities/dynimport.py
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# abstract_utilities/dynimport.py
|
|
2
2
|
from __future__ import annotations
|
|
3
|
-
import importlib, sys, os
|
|
4
3
|
from functools import lru_cache
|
|
5
|
-
from typing import
|
|
6
|
-
import
|
|
4
|
+
from typing import *
|
|
5
|
+
import importlib, sys, os, sys
|
|
6
|
+
from typing import Optional
|
|
7
7
|
from importlib import import_module
|
|
8
8
|
from .type_utils import make_list
|
|
9
|
-
|
|
9
|
+
|
|
10
10
|
class _LazyAttr:
|
|
11
11
|
"""Lazy resolver proxy to avoid import-time cycles.
|
|
12
12
|
First use triggers actual import & attribute lookup.
|
|
@@ -181,14 +181,6 @@ def get_many_module_imports(*args):
|
|
|
181
181
|
all_modules[symbol] = get_abstract_import(module = module,symbol=symbol)
|
|
182
182
|
import_symbols(all_modules)
|
|
183
183
|
return all_modules
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
def get_caller_dir():
|
|
188
|
-
frame = inspect.stack()[1]
|
|
189
|
-
abspath = os.path.abspath(frame.filename)
|
|
190
|
-
return os.path.dirname(abspath)
|
|
191
|
-
def call_for_all_tabs(root=None):
|
|
192
|
-
|
|
193
|
-
root = root or get_caller_dir()
|
|
194
|
-
get_for_all_tabs(root)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
|
abstract_utilities/log_utils.py
CHANGED
|
@@ -229,7 +229,7 @@ def initialize_call_log(value=None,
|
|
|
229
229
|
|
|
230
230
|
print_or_log(full_message,level=log_level)
|
|
231
231
|
|
|
232
|
-
def get_json_call_response(value, status_code, data=None, logMsg=None, callLog=False):
|
|
232
|
+
def get_json_call_response(value=None, status_code=None, data=None, logMsg=None, callLog=False):
|
|
233
233
|
response_body = {}
|
|
234
234
|
if status_code == 200:
|
|
235
235
|
response_body["success"] = True
|
abstract_utilities/path_utils.py
CHANGED
|
@@ -27,12 +27,9 @@ from .read_write_utils import read_from_file,write_to_file
|
|
|
27
27
|
from .string_clean import eatAll
|
|
28
28
|
from .list_utils import make_list
|
|
29
29
|
from .type_utils import get_media_exts, is_media_type,MIME_TYPES
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def get_caller_dir(i=1):
|
|
34
|
-
abspath = get_caller_path(i+1)
|
|
35
|
-
return os.path.dirname(abspath)
|
|
30
|
+
from .safe_utils import safe_join
|
|
31
|
+
from .class_utils import get_caller_path.get_caller_dir
|
|
32
|
+
|
|
36
33
|
def get_os_info():
|
|
37
34
|
"""
|
|
38
35
|
Get Operating System Information
|
|
@@ -600,6 +597,45 @@ def get_safe_filename(path=None,basename=None):
|
|
|
600
597
|
def get_safe_ext(path=None,basename=None):
|
|
601
598
|
_,ext = get_safe_splitext(path=path,basename=basename)
|
|
602
599
|
return ext
|
|
600
|
+
def raw_create_dirs(*paths):
|
|
601
|
+
"""Recursively create all directories along the given path."""
|
|
602
|
+
full_path = os.path.abspath(safe_join(*paths))
|
|
603
|
+
sub_parts = [p for p in full_path.split(os.sep) if p]
|
|
604
|
+
|
|
605
|
+
current_path = "/" if full_path.startswith(os.sep) else ""
|
|
606
|
+
for part in sub_parts:
|
|
607
|
+
current_path = safe_join(current_path, part)
|
|
608
|
+
os.makedirs(current_path, exist_ok=True)
|
|
609
|
+
return full_path
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def create_dirs(directory, child=None):
|
|
613
|
+
"""Create directory and optional child path safely."""
|
|
614
|
+
full_path = os.path.abspath(safe_join(directory, child))
|
|
615
|
+
if not os.path.exists(full_path):
|
|
616
|
+
raw_create_dirs(full_path)
|
|
617
|
+
return full_path
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def get_base_dir(directory=None):
|
|
621
|
+
"""Return given directory or _BASE_DIR fallback."""
|
|
622
|
+
return directory or _BASE_DIR
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def create_base_path(directory=None, child=None):
|
|
626
|
+
"""Join base dir with child."""
|
|
627
|
+
directory = get_base_dir(directory)
|
|
628
|
+
return safe_join(directory, child)
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def create_base_dir(directory=None, child=None):
|
|
632
|
+
"""Ensure existence of base directory path."""
|
|
633
|
+
full_path = create_base_path(directory, child)
|
|
634
|
+
if not os.path.exists(full_path):
|
|
635
|
+
raw_create_dirs(full_path)
|
|
636
|
+
return full_path
|
|
637
|
+
|
|
638
|
+
|
|
603
639
|
|
|
604
640
|
def get_file_parts(path):
|
|
605
641
|
|
|
@@ -1,115 +1,37 @@
|
|
|
1
1
|
"""
|
|
2
2
|
read_write_utils.py
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
-------------------
|
|
4
|
+
Unified read/write utility for safe file operations.
|
|
5
|
+
Supports:
|
|
6
|
+
- Writing content to a file
|
|
7
|
+
- Reading content from a file
|
|
8
|
+
- Creating and reading if missing
|
|
9
|
+
- Detecting file/content params via positional args or kwargs
|
|
6
10
|
|
|
7
11
|
Usage:
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
1. Write content to a file.
|
|
11
|
-
2. Read content from a file.
|
|
12
|
-
3. Check if a string has a file extension.
|
|
13
|
-
4. Read from or write to a file depending on the number of arguments.
|
|
14
|
-
5. Create a file if it does not exist, then read from it.
|
|
12
|
+
from abstract_utilities.read_write_utils import *
|
|
13
|
+
"""
|
|
15
14
|
|
|
16
|
-
Each function includes a docstring to further explain its purpose, input parameters, and return values.
|
|
17
15
|
import os
|
|
18
16
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
os.remove(path) # Remove a file
|
|
22
|
-
os.unlink(path) # Alias for os.remove()
|
|
23
|
-
os.rmdir(path) # Remove an empty directory
|
|
24
|
-
os.makedirs(path) # Create directories recursively
|
|
25
|
-
os.makedirs(path, exist_ok=True) # Create directories, ignore if exists
|
|
26
|
-
os.mkdir(path) # Create a single directory
|
|
27
|
-
os.listdir(path) # List files and directories in a path
|
|
28
|
-
os.chdir(path) # Change current working directory
|
|
29
|
-
os.getcwd() # Get current working directory
|
|
30
|
-
os.stat(path) # Get file/directory information
|
|
31
|
-
os.lstat(path) # Get symbolic link information
|
|
32
|
-
os.symlink(src, dst) # Create a symbolic link
|
|
33
|
-
os.readlink(path) # Read the target of a symbolic link
|
|
34
|
-
os.getcwd() # Get current working directory
|
|
35
|
-
os.chdir(path) # Change current working directory
|
|
36
|
-
|
|
37
|
-
# File and Directory Information
|
|
38
|
-
os.path.exists(path) # Check if a path exists
|
|
39
|
-
os.path.isfile(path) # Check if a path points to a file
|
|
40
|
-
os.path.isdir(path) # Check if a path points to a directory
|
|
41
|
-
os.path.islink(path) # Check if a path points to a symbolic link
|
|
42
|
-
os.path.abspath(path) # Get the absolute path of a file/directory
|
|
43
|
-
os.path.basename(path) # Get the base name of a path
|
|
44
|
-
os.path.dirname(path) # Get the directory name of a path
|
|
45
|
-
os.path.join(path1, path2, ...) # Join path components into a single path
|
|
46
|
-
|
|
47
|
-
# File Permissions
|
|
48
|
-
os.chmod(path, mode) # Change file permissions
|
|
49
|
-
os.access(path, mode) # Check if a file is accessible with given mode
|
|
50
|
-
|
|
51
|
-
# File Times
|
|
52
|
-
os.path.getatime(path) # Get last access time of a file
|
|
53
|
-
os.path.getmtime(path) # Get last modification time of a file
|
|
54
|
-
os.path.getctime(path) # Get creation time of a file
|
|
55
|
-
os.utime(path, times) # Set access and modification times
|
|
56
|
-
|
|
57
|
-
# Working with Paths
|
|
58
|
-
os.path.split(path) # Split a path into (head, tail)
|
|
59
|
-
os.path.splitext(path) # Split a path into (root, ext)
|
|
60
|
-
os.path.normpath(path) # Normalize a path (e.g., convert slashes)
|
|
61
|
-
|
|
62
|
-
# Other
|
|
63
|
-
os.path.samefile(path1, path2) # Check if two paths refer to the same file
|
|
64
|
-
|
|
65
|
-
# Directory Traversal
|
|
66
|
-
for root, dirs, files in os.walk(top, topdown=True):
|
|
67
|
-
# Traverse a directory tree, yielding root, dirs, and files lists
|
|
68
|
-
|
|
69
|
-
# Temporary Files and Directories
|
|
70
|
-
import tempfile
|
|
71
|
-
tempfile.mkstemp() # Create a temporary file
|
|
72
|
-
tempfile.mkdtemp() # Create a temporary directory
|
|
73
|
-
tempfile.TemporaryFile() # Create a temporary file object
|
|
74
|
-
|
|
75
|
-
# Environment Variables
|
|
76
|
-
os.environ # Dictionary of environment variables
|
|
77
|
-
os.environ['VAR_NAME'] # Access an environment variable
|
|
78
|
-
os.environ.get('VAR_NAME') # Access an environment variable (with default)
|
|
79
|
-
|
|
80
|
-
# Path Manipulation
|
|
81
|
-
os.path.abspath(path) # Convert relative path to absolute path
|
|
82
|
-
os.path.join(path1, path2, ...) # Join paths together
|
|
83
|
-
os.path.split(path) # Split a path into directory and filename
|
|
84
|
-
os.path.dirname(path) # Get the directory part of a path
|
|
85
|
-
os.path.basename(path) # Get the filename part of a path
|
|
86
|
-
os.path.exists(path) # Check if a path exists
|
|
87
|
-
os.path.isfile(path) # Check if a path points to a file
|
|
88
|
-
os.path.isdir(path) # Check if a path points to a directory
|
|
89
|
-
|
|
90
|
-
# File Permissions
|
|
91
|
-
os.chmod(path, mode) # Change file permissions
|
|
92
|
-
|
|
93
|
-
# Miscellaneous
|
|
94
|
-
os.getpid() # Get the current process ID
|
|
95
|
-
os.getlogin() # Get the name of the logged-in user
|
|
17
|
+
_FILE_PATH_KEYS = ['file', 'filepath', 'file_path', 'path', 'directory', 'f', 'dst', 'dest']
|
|
18
|
+
_CONTENTS_KEYS = ['cont', 'content', 'contents', 'data', 'datas', 'dat', 'src', 'source']
|
|
96
19
|
|
|
97
|
-
"""
|
|
98
|
-
import os
|
|
99
|
-
def break_down_find_existing(path):
|
|
100
|
-
test_path = ''
|
|
101
|
-
for part in path.split(os.sep):
|
|
102
|
-
test_path = os.path.join(test_path, part)
|
|
103
|
-
if not os.path.exists(test_path):
|
|
104
|
-
return test_path if test_path else None
|
|
105
|
-
return test_path
|
|
106
20
|
|
|
21
|
+
# --- Helper utilities --------------------------------------------------------
|
|
107
22
|
def string_in_keys(strings, kwargs):
|
|
108
|
-
|
|
23
|
+
"""Find a matching keyword in kwargs that contains any of the given substrings."""
|
|
24
|
+
for key in kwargs:
|
|
25
|
+
for s in strings:
|
|
26
|
+
if s.lower() in key.lower():
|
|
27
|
+
return key
|
|
28
|
+
return None
|
|
29
|
+
|
|
109
30
|
|
|
110
31
|
def get_path(paths):
|
|
32
|
+
"""Return the first valid path among given paths."""
|
|
111
33
|
for path in paths:
|
|
112
|
-
if isinstance(path,str):
|
|
34
|
+
if isinstance(path, str):
|
|
113
35
|
if os.path.isfile(path):
|
|
114
36
|
return path
|
|
115
37
|
dirname = os.path.dirname(path)
|
|
@@ -117,83 +39,97 @@ def get_path(paths):
|
|
|
117
39
|
return path
|
|
118
40
|
return None
|
|
119
41
|
|
|
42
|
+
|
|
43
|
+
def break_down_find_existing(path):
|
|
44
|
+
"""Return the first non-existent subpath within a path chain."""
|
|
45
|
+
test_path = ''
|
|
46
|
+
for part in path.split(os.sep):
|
|
47
|
+
test_path = os.path.join(test_path, part)
|
|
48
|
+
if not os.path.exists(test_path):
|
|
49
|
+
return test_path if test_path else None
|
|
50
|
+
return test_path
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# --- Parameter parsing --------------------------------------------------------
|
|
120
54
|
def check_read_write_params(*args, **kwargs):
|
|
121
|
-
|
|
122
|
-
contents
|
|
123
|
-
|
|
124
|
-
|
|
55
|
+
"""
|
|
56
|
+
Determine file_path and contents from arguments.
|
|
57
|
+
Returns a tuple: (file_path, contents)
|
|
58
|
+
"""
|
|
59
|
+
file_key = string_in_keys(_FILE_PATH_KEYS, kwargs)
|
|
60
|
+
content_key = string_in_keys(_CONTENTS_KEYS, kwargs)
|
|
61
|
+
|
|
62
|
+
file_path = kwargs.get(file_key) if file_key else None
|
|
63
|
+
contents = kwargs.get(content_key) if content_key else None
|
|
125
64
|
|
|
126
|
-
# Handle positional
|
|
65
|
+
# Handle positional args (fallback)
|
|
127
66
|
if file_path is None and len(args) > 0:
|
|
128
67
|
file_path = args[0]
|
|
129
68
|
if contents is None and len(args) > 1:
|
|
130
69
|
contents = args[1]
|
|
131
|
-
elif contents is None and len(args) > 0 and file_path != args[0]:
|
|
132
|
-
contents = args[0]
|
|
133
|
-
|
|
134
|
-
if file_path is None or contents is None:
|
|
135
|
-
raise ValueError("Both 'file_path' and 'contents' (or 'data') are required.")
|
|
136
70
|
|
|
71
|
+
if file_path is None:
|
|
72
|
+
raise ValueError("Missing file_path argument.")
|
|
137
73
|
return file_path, contents
|
|
138
74
|
|
|
139
|
-
|
|
75
|
+
|
|
76
|
+
# --- Core functionality -------------------------------------------------------
|
|
77
|
+
def write_to_file(*args, **kwargs):
|
|
140
78
|
"""
|
|
141
|
-
Write contents to a file
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
file_path: The path of the file to write to.
|
|
145
|
-
contents: The content to write to the file.
|
|
146
|
-
|
|
147
|
-
Returns:
|
|
148
|
-
The contents that were written to the file.
|
|
79
|
+
Write contents to a file (create if missing).
|
|
80
|
+
|
|
81
|
+
Returns the file_path written.
|
|
149
82
|
"""
|
|
150
|
-
|
|
151
|
-
if
|
|
152
|
-
|
|
153
|
-
f.write(params[1])
|
|
154
|
-
return contents
|
|
83
|
+
file_path, contents = check_read_write_params(*args, **kwargs)
|
|
84
|
+
if contents is None:
|
|
85
|
+
raise ValueError("Missing contents to write.")
|
|
155
86
|
|
|
87
|
+
os.makedirs(os.path.dirname(file_path) or ".", exist_ok=True)
|
|
88
|
+
with open(file_path, "w", encoding="utf-8") as f:
|
|
89
|
+
f.write(str(contents))
|
|
90
|
+
return file_path
|
|
156
91
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
Read
|
|
160
|
-
|
|
161
|
-
Args:
|
|
162
|
-
file_path: The path of the file to read from.
|
|
163
|
-
|
|
164
|
-
Returns:
|
|
165
|
-
The contents of the file.
|
|
166
|
-
"""
|
|
167
|
-
with open(file_path, 'r', encoding='UTF-8') as f:
|
|
92
|
+
|
|
93
|
+
def read_from_file(file_path):
|
|
94
|
+
"""Read text content from a file."""
|
|
95
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
168
96
|
return f.read()
|
|
169
97
|
|
|
170
|
-
|
|
98
|
+
|
|
99
|
+
def create_and_read_file(*args, **kwargs):
|
|
171
100
|
"""
|
|
172
|
-
Create
|
|
173
|
-
|
|
174
|
-
Args:
|
|
175
|
-
file_path: The path of the file to create and read from.
|
|
176
|
-
contents: The content to write to the file if it does not exist.
|
|
177
|
-
|
|
178
|
-
Returns:
|
|
179
|
-
The contents of the file.
|
|
101
|
+
Create the file (if missing) and read contents from it.
|
|
180
102
|
"""
|
|
103
|
+
file_path, contents = check_read_write_params(*args, **kwargs)
|
|
181
104
|
if not os.path.isfile(file_path):
|
|
182
|
-
write_to_file(
|
|
105
|
+
write_to_file(file_path, contents or "")
|
|
183
106
|
return read_from_file(file_path)
|
|
107
|
+
|
|
108
|
+
|
|
184
109
|
def is_file_extension(obj: str) -> bool:
|
|
185
|
-
"""
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
Returns:
|
|
192
|
-
True if the string has a file extension, False otherwise.
|
|
193
|
-
"""
|
|
194
|
-
return len(obj) >= 4 and '.' in obj[-4:-3]
|
|
110
|
+
"""Return True if obj looks like a filename with extension."""
|
|
111
|
+
if not isinstance(obj, str):
|
|
112
|
+
return False
|
|
113
|
+
root, ext = os.path.splitext(obj)
|
|
114
|
+
return bool(root and ext)
|
|
115
|
+
|
|
195
116
|
|
|
196
117
|
def delete_file(file_path: str):
|
|
118
|
+
"""Safely delete a file if it exists."""
|
|
197
119
|
if os.path.isfile(file_path):
|
|
198
120
|
os.remove(file_path)
|
|
121
|
+
return True
|
|
122
|
+
return False
|
|
123
|
+
|
|
199
124
|
|
|
125
|
+
def get_content_lines(*args, **kwargs):
|
|
126
|
+
"""Return a list of lines from string or file path."""
|
|
127
|
+
file_path, contents = check_read_write_params(*args, **kwargs)
|
|
128
|
+
if os.path.isfile(file_path):
|
|
129
|
+
contents = read_from_file(filepath)
|
|
130
|
+
|
|
131
|
+
if isinstance(contents, str):
|
|
132
|
+
return contents.splitlines()
|
|
133
|
+
elif isinstance(contents, list):
|
|
134
|
+
return contents
|
|
135
|
+
return []
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""
|
|
2
|
+
abstract_safeops.py
|
|
3
|
+
-------------------
|
|
4
|
+
Utility functions for safely splitting, slicing, and retrieving elements from iterable or string objects
|
|
5
|
+
without raising exceptions on invalid input or out-of-range indices.
|
|
6
|
+
|
|
7
|
+
Designed for compatibility with the abstract_ ecosystem (e.g. abstract_utilities, abstract_math, etc.).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import *
|
|
11
|
+
from .type_utils import is_number
|
|
12
|
+
from .class_utils import get_caller_dir
|
|
13
|
+
|
|
14
|
+
_BASE_DIR = get_caller_dir()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def safe_split(
|
|
18
|
+
string: Any,
|
|
19
|
+
char: Any,
|
|
20
|
+
i: Optional[int] = None,
|
|
21
|
+
default: Union[bool, Any] = False
|
|
22
|
+
) -> Union[str, List[str], Any, None]:
|
|
23
|
+
"""
|
|
24
|
+
Safely split a string by a character and optionally return index i.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
string: Input string (or any object convertible to string).
|
|
28
|
+
char: Delimiter to split on.
|
|
29
|
+
i: Optional index to retrieve from the split result.
|
|
30
|
+
default: If True, return the original string on error.
|
|
31
|
+
If any other value, return that instead of raising.
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
The split list, or the element at index i, or default behavior on error.
|
|
35
|
+
"""
|
|
36
|
+
if string is None or char is None:
|
|
37
|
+
return string
|
|
38
|
+
|
|
39
|
+
s, c = str(string), str(char)
|
|
40
|
+
if c not in s:
|
|
41
|
+
return string
|
|
42
|
+
|
|
43
|
+
parts = s.split(c)
|
|
44
|
+
|
|
45
|
+
if i is None:
|
|
46
|
+
return parts
|
|
47
|
+
|
|
48
|
+
if is_number(i):
|
|
49
|
+
idx = int(i)
|
|
50
|
+
if 0 <= idx < len(parts):
|
|
51
|
+
return parts[idx]
|
|
52
|
+
|
|
53
|
+
if default:
|
|
54
|
+
return string if default is True else default
|
|
55
|
+
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def safe_slice(
|
|
60
|
+
obj: Any,
|
|
61
|
+
i: Optional[int] = None,
|
|
62
|
+
k: Optional[int] = None,
|
|
63
|
+
default: Union[bool, Any] = False
|
|
64
|
+
) -> Any:
|
|
65
|
+
"""
|
|
66
|
+
Safely slice an iterable object or string, with fallback behavior on invalid indices.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
obj: Iterable or string-like object.
|
|
70
|
+
i: Start index (can be negative).
|
|
71
|
+
k: End index (can be negative).
|
|
72
|
+
default: If True, returns the original object on error.
|
|
73
|
+
If any other value, return that value on error.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
The sliced object, or default behavior on error.
|
|
77
|
+
"""
|
|
78
|
+
# Null or invalid base case
|
|
79
|
+
if obj is None or isinstance(obj, bool):
|
|
80
|
+
return obj if default is True else default if default else None
|
|
81
|
+
|
|
82
|
+
# Non-iterable guard
|
|
83
|
+
if not hasattr(obj, "__getitem__"):
|
|
84
|
+
return obj if default is True else default if default else None
|
|
85
|
+
|
|
86
|
+
obj_len = len(obj)
|
|
87
|
+
|
|
88
|
+
# Normalize negative indices
|
|
89
|
+
if isinstance(i, int) and i < 0:
|
|
90
|
+
i = obj_len + i
|
|
91
|
+
if isinstance(k, int) and k < 0:
|
|
92
|
+
k = obj_len + k
|
|
93
|
+
|
|
94
|
+
# Bound indices
|
|
95
|
+
if i is not None:
|
|
96
|
+
i = max(0, min(i, obj_len))
|
|
97
|
+
if k is not None:
|
|
98
|
+
k = max(0, min(k, obj_len))
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
return obj[i:k]
|
|
102
|
+
except Exception:
|
|
103
|
+
return obj if default is True else default if default else None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def safe_get(
|
|
107
|
+
obj: Any,
|
|
108
|
+
key: Union[int, str, None] = None,
|
|
109
|
+
default: Union[bool, Any] = False
|
|
110
|
+
) -> Any:
|
|
111
|
+
"""
|
|
112
|
+
Generalized safe getter for both indexable and mapping types.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
obj: The object to access (list, dict, string, etc.).
|
|
116
|
+
key: Index or key to retrieve.
|
|
117
|
+
default: Fallback value or True for "return obj".
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
Retrieved element, or default value on failure.
|
|
121
|
+
"""
|
|
122
|
+
if obj is None or key is None:
|
|
123
|
+
return obj if default is True else default if default else None
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
if isinstance(obj, dict):
|
|
127
|
+
return obj.get(key, obj if default is True else default if default else None)
|
|
128
|
+
return obj[key]
|
|
129
|
+
except Exception:
|
|
130
|
+
return obj if default is True else default if default else None
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: abstract_utilities
|
|
3
|
-
Version: 0.2.2.
|
|
3
|
+
Version: 0.2.2.437
|
|
4
4
|
Summary: abstract_utilities is a collection of utility modules providing a variety of functions to aid in tasks such as data comparison, list manipulation, JSON handling, string manipulation, mathematical computations, and time operations.
|
|
5
5
|
Home-page: https://github.com/AbstractEndeavors/abstract_utilities
|
|
6
6
|
Author: putkoff
|
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
abstract_utilities/__init__.py,sha256=9lHec_X7PqSZgZQSb9huHFSP0KPKRRF0LI3XfzmdeVE,5102
|
|
2
2
|
abstract_utilities/abstract_classes.py,sha256=A6-FNDQb2P_jcyt01Kc5SuY2QawLVKNjQ-rDGfsn4rA,2461
|
|
3
|
-
abstract_utilities/class_utils.py,sha256
|
|
3
|
+
abstract_utilities/class_utils.py,sha256=YMQgeTHSMo2C13G0JRgQIgbx131jb-PHdDrIqt71FsE,13664
|
|
4
4
|
abstract_utilities/collator_utils.py,sha256=9exNoZAr9rABGYTwZOn7hdLbpnMtRd2AgfU7yjZrXGw,2348
|
|
5
5
|
abstract_utilities/doit.py,sha256=a1zkyMJbSGPvE-OmCQcH_dQyLME392UfvQmGztOWyhE,1646
|
|
6
|
-
abstract_utilities/dynimport.py,sha256=
|
|
6
|
+
abstract_utilities/dynimport.py,sha256=L2xT2zIMl9chbYb-KutXB7bzc7k25dlv1hfGx6Yb-Zk,6576
|
|
7
7
|
abstract_utilities/error_utils.py,sha256=dSMIM3TKe4e9i_akObyjDwy3Zu4fnoWRK9hucg_ryZo,890
|
|
8
8
|
abstract_utilities/global_utils.py,sha256=UkCS1nE561bVbxWsH-YQdFPSeZFMYXV7xg-DAtGUvrI,2204
|
|
9
9
|
abstract_utilities/hash_utils.py,sha256=u7t209ERD9aGONZHqmkYtiQRRadD2qG5ICSTxlYlZMc,206
|
|
10
10
|
abstract_utilities/history_utils.py,sha256=2bG8hMSRzLWMae4mpd2sf1esYtqT2D_3MDxeJnAE2Jw,1633
|
|
11
11
|
abstract_utilities/json_utils.py,sha256=YA4zoBRAsVjdU-BjFd1L5z81Y5X-NuwKrQW5L992EY4,27609
|
|
12
12
|
abstract_utilities/list_utils.py,sha256=i1fZ_kZ0mf_ei6w0MOkuEieRiyF-ReeAXzIdoRI1cvo,6298
|
|
13
|
-
abstract_utilities/log_utils.py,sha256=
|
|
13
|
+
abstract_utilities/log_utils.py,sha256=W74Y-CmdQP4Kj88HmAgejVxWgyWlvgCKMwLvOfyFf9c,9393
|
|
14
14
|
abstract_utilities/math_utils.py,sha256=0o1ls1En03UAkYmxTBildCCJDfHygmNuvVnrNrLYtK0,6578
|
|
15
15
|
abstract_utilities/parse_utils.py,sha256=Z5OGRwHuzCzY91fz0JJojk1BPAo1XF2quNNLuBF4_Vk,18602
|
|
16
|
-
abstract_utilities/path_utils.py,sha256=
|
|
17
|
-
abstract_utilities/read_write_utils.py,sha256=
|
|
16
|
+
abstract_utilities/path_utils.py,sha256=EE9NGd6zkwM3UMp7TcfB-E4-nnzg_WEnkyOeZOpb0Rk,19252
|
|
17
|
+
abstract_utilities/read_write_utils.py,sha256=EV4r8nlLKxtpukR9xRZBk49HGRyLHOg8QvdGjALQ1BM,4102
|
|
18
|
+
abstract_utilities/safe_utils.py,sha256=7Mn_5Z-4qwoKPI7dd8znz3x8uhjwbQ2oOFJ-w7DNgKg,3610
|
|
18
19
|
abstract_utilities/string_clean.py,sha256=-gY9i2yqjX5UClvSaKsSrzA4GjR7eaNI3GnFjZpt2bo,5923
|
|
19
20
|
abstract_utilities/tetsts.py,sha256=PrejTUew5dAAqNb4erMJwfdSHxDyuuHGWY2fMlWk5hk,21
|
|
20
21
|
abstract_utilities/thread_utils.py,sha256=LhE1ylSuOKkkMErBf6SjZprjO_vfh3IKfvNKJQiCxho,5460
|
|
@@ -52,7 +53,7 @@ abstract_utilities/file_utils/imports/classes.py,sha256=zw16D_h5AxJiks4ydbqkWkXV
|
|
|
52
53
|
abstract_utilities/file_utils/imports/constants.py,sha256=eIeSj48vtfa8CTYKuuZXbgJQepBrMracfVguaSuN41U,1626
|
|
53
54
|
abstract_utilities/file_utils/imports/file_functions.py,sha256=25yta20DDsdgenXYjpm4Ma3Fd6WK9Q16EjyhcZubDFg,291
|
|
54
55
|
abstract_utilities/file_utils/imports/imports.py,sha256=mrXR2rEpb12Wve91eQehSxwR-gqc_UxJnqBKTrf7hjU,538
|
|
55
|
-
abstract_utilities/file_utils/imports/module_imports.py,sha256=
|
|
56
|
+
abstract_utilities/file_utils/imports/module_imports.py,sha256=x3WPeyO4fEwW0RRS3C5NCO_aXRdNps84oN0oN1W65tA,387
|
|
56
57
|
abstract_utilities/robust_reader/__init__.py,sha256=4i6qW4lwhdYuoO5-p9Xbt8Lpmr3hzCh9Rgb9y19QJwk,28
|
|
57
58
|
abstract_utilities/robust_reader/file_reader2.py,sha256=U-5opkLu-bct091Eb-5CiNBTf0UFoSITYi8zR-Sz38w,25077
|
|
58
59
|
abstract_utilities/robust_reader/file_readers.py,sha256=U-5opkLu-bct091Eb-5CiNBTf0UFoSITYi8zR-Sz38w,25077
|
|
@@ -75,7 +76,7 @@ abstract_utilities/ssh_utils/classes.py,sha256=3Q9BfLpyagNFYyiF4bt-5UCezeUJv9NK9
|
|
|
75
76
|
abstract_utilities/ssh_utils/imports.py,sha256=7-pVJK1RfR0KiZsv0mNYGPuNXA4iYqmDvqbAR9h1llU,371
|
|
76
77
|
abstract_utilities/ssh_utils/pexpect_utils.py,sha256=JBdOIXBTXAqE5TrsFjmPWJgwSaWyRJN8rbJ6y3_zKPY,10556
|
|
77
78
|
abstract_utilities/ssh_utils/utils.py,sha256=smUWAx3nW1h0etTndJ_te9bkUX5YzQ8kYd9_gD1TXLk,4882
|
|
78
|
-
abstract_utilities-0.2.2.
|
|
79
|
-
abstract_utilities-0.2.2.
|
|
80
|
-
abstract_utilities-0.2.2.
|
|
81
|
-
abstract_utilities-0.2.2.
|
|
79
|
+
abstract_utilities-0.2.2.437.dist-info/METADATA,sha256=eiw9SPy932pYkCj0SvstHkoNfZIZNfzeZv7Gq7eIDCM,28108
|
|
80
|
+
abstract_utilities-0.2.2.437.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
81
|
+
abstract_utilities-0.2.2.437.dist-info/top_level.txt,sha256=BF0GZ0xVFfN1K-hFIWPO3viNsOs1sSF86n1vHBg39FM,19
|
|
82
|
+
abstract_utilities-0.2.2.437.dist-info/RECORD,,
|
|
File without changes
|
{abstract_utilities-0.2.2.436.dist-info → abstract_utilities-0.2.2.437.dist-info}/top_level.txt
RENAMED
|
File without changes
|