Skip to content

Commit 47b460e

Browse files
committed
adjust docstrings and rename certain internal params to clarify their usage
1 parent 549817f commit 47b460e

4 files changed

Lines changed: 71 additions & 69 deletions

File tree

src/xulbux/data.py

Lines changed: 42 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -247,8 +247,8 @@ def is_equal(
247247
ignore_paths = [ignore_paths]
248248

249249
return cls._compare_nested(
250-
d1=cls.remove_comments(data1, comment_start, comment_end),
251-
d2=cls.remove_comments(data2, comment_start, comment_end),
250+
data1=cls.remove_comments(data1, comment_start, comment_end),
251+
data2=cls.remove_comments(data2, comment_start, comment_end),
252252
ignore_paths=[str(path).split(path_sep) for path in ignore_paths if path],
253253
)
254254

@@ -339,14 +339,11 @@ def set_value_by_path_id(cls, data: DataStructure, update_values: dict[str, Any]
339339
{ "1>012": "new value", "1>31": ["new value 1", "new value 2"], ... }
340340
```
341341
The path IDs should have been created using `Data.get_path_id()`."""
342-
343-
valid_entries = [(path_id, new_val) for path_id, new_val in update_values.items()]
344-
if not valid_entries:
342+
if not (valid_update_values := [(path_id, new_val) for path_id, new_val in update_values.items()]):
345343
raise ValueError(f"No valid 'update_values' found in dictionary:\n{update_values!r}")
346344

347-
for path_id, new_val in valid_entries:
348-
path = cls._sep_path_id(path_id)
349-
data = cls._set_nested_val(data, path, new_val)
345+
for path_id, new_val in valid_update_values:
346+
data = cls._set_nested_val(data, id_path=cls._sep_path_id(path_id), value=new_val)
350347

351348
return data
352349

@@ -464,33 +461,33 @@ def print(
464461
@classmethod
465462
def _compare_nested(
466463
cls,
467-
d1: DataStructure,
468-
d2: DataStructure,
464+
data1: DataStructure,
465+
data2: DataStructure,
469466
ignore_paths: list[list[str]],
470467
current_path: list[str] = [],
471468
) -> bool:
472469
if any(current_path == path[:len(current_path)] for path in ignore_paths):
473470
return True
474-
if type(d1) is not type(d2):
471+
if type(data1) is not type(data2):
475472
return False
476-
if isinstance(d1, dict) and isinstance(d2, dict):
477-
if set(d1.keys()) != set(d2.keys()):
473+
if isinstance(data1, dict) and isinstance(data2, dict):
474+
if set(data1.keys()) != set(data2.keys()):
478475
return False
479-
return all(cls._compare_nested(d1[key], d2[key], ignore_paths, current_path + [key]) for key in d1)
480-
if isinstance(d1, (list, tuple)):
481-
if len(d1) != len(d2):
476+
return all(cls._compare_nested(data1[key], data2[key], ignore_paths, current_path + [key]) for key in data1)
477+
if isinstance(data1, (list, tuple)):
478+
if len(data1) != len(data2):
482479
return False
483480
return all(
484481
cls._compare_nested(item1, item2, ignore_paths, current_path + [str(i)])
485-
for i, (item1, item2) in enumerate(zip(d1, d2))
482+
for i, (item1, item2) in enumerate(zip(data1, data2))
486483
)
487-
if isinstance(d1, (set, frozenset)):
488-
return d1 == d2
489-
return d1 == d2
484+
if isinstance(data1, (set, frozenset)):
485+
return data1 == data2
486+
return data1 == data2
490487

491488
@staticmethod
492489
def _sep_path_id(path_id: str) -> list[int]:
493-
"""Internal method to separate a path ID into its ID parts."""
490+
"""Internal method to separate a path-ID string into its ID parts as a list of integers."""
494491
if len(split_id := path_id.split(">")) == 2:
495492
id_part_len, path_id_parts = split_id
496493

@@ -546,23 +543,24 @@ def _get_path_id(path: str, path_sep: str, data_obj: DataStructure, ignore_not_f
546543
return f"{max_id_length}>{''.join(id.zfill(max_id_length) for id in path_ids)}"
547544

548545
@classmethod
549-
def _set_nested_val(cls, data: DataStructure, path: list[int], value: Any) -> DataStructure:
550-
if len(path) == 1:
546+
def _set_nested_val(cls, data: DataStructure, id_path: list[int], value: Any) -> DataStructure:
547+
"""Internal method to set a value in a nested data structure based on the provided ID path."""
548+
if len(id_path) == 1:
551549
if isinstance(data, dict):
552550
keys, data = list(data.keys()), dict(data)
553-
data[keys[path[0]]] = value
551+
data[keys[id_path[0]]] = value
554552
elif isinstance(data, IndexIterableTypes):
555553
was_t, data = type(data), list(data)
556-
data[path[0]] = value
554+
data[id_path[0]] = value
557555
data = was_t(data)
558556

559557
else:
560558
if isinstance(data, dict):
561559
keys, data = list(data.keys()), dict(data)
562-
data[keys[path[0]]] = cls._set_nested_val(data[keys[path[0]]], path[1:], value)
560+
data[keys[id_path[0]]] = cls._set_nested_val(data[keys[id_path[0]]], id_path[1:], value)
563561
elif isinstance(data, IndexIterableTypes):
564562
was_t, data = type(data), list(data)
565-
data[path[0]] = cls._set_nested_val(data[path[0]], path[1:], value)
563+
data[id_path[0]] = cls._set_nested_val(data[id_path[0]], id_path[1:], value)
566564
data = was_t(data)
567565

568566
return data
@@ -588,30 +586,31 @@ def __init__(self, data: DataStructure, comment_start: str, comment_end: str, co
588586
)) if len(comment_end) > 0 else None
589587

590588
def __call__(self) -> DataStructure:
591-
return self._rem_nested_comments(self.data)
589+
return self.rem_nested_comments(self.data)
592590

593-
def _rem_nested_comments(self, item: Any) -> Any:
591+
def rem_nested_comments(self, item: Any) -> Any:
594592
if isinstance(item, dict):
595593
return {
596-
k: v
597-
for k, v in ((self._rem_nested_comments(key), self._rem_nested_comments(value)) for key, value in item.items())
598-
if k is not None
594+
key: val
595+
for key, val in ( \
596+
(self.rem_nested_comments(k), self.rem_nested_comments(v)) for k, v in item.items()
597+
) if key is not None
599598
}
599+
600600
if isinstance(item, IndexIterableTypes):
601-
processed = (v for v in map(self._rem_nested_comments, item) if v is not None)
601+
processed = (v for v in map(self.rem_nested_comments, item) if v is not None)
602602
return type(item)(processed)
603+
603604
if isinstance(item, str):
604-
return self._remove_str_comment(item)
605-
return item
605+
if self.pattern:
606+
if (match := self.pattern.match(item)):
607+
start, end = match.group(1).strip(), match.group(2).strip()
608+
return f"{start}{self.comment_sep if start and end else ''}{end}" or None
609+
return item.strip() or None
610+
else:
611+
return None if item.lstrip().startswith(self.comment_start) else item.strip() or None
606612

607-
def _remove_str_comment(self, s: str) -> Optional[str]:
608-
if self.pattern:
609-
if (match := self.pattern.match(s)):
610-
start, end = match.group(1).strip(), match.group(2).strip()
611-
return f"{start}{self.comment_sep if start and end else ''}{end}" or None
612-
return s.strip() or None
613-
else:
614-
return None if s.lstrip().startswith(self.comment_start) else s.strip() or None
613+
return item
615614

616615

617616
class _DataRenderHelper:

src/xulbux/env_path.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,9 @@ def remove_path(cls, path: Optional[str] = None, cwd: bool = False, base_dir: bo
5353

5454
@staticmethod
5555
def _get(path: Optional[str] = None, cwd: bool = False, base_dir: bool = False) -> str:
56-
"""Get and/or normalize the given path, CWD or base directory.\n
57-
------------------------------------------------------------------------------------
58-
Raise an error if no path is provided and neither `cwd` or `base_dir` is `True`."""
56+
"""Internal method to get the normalized `path`, CWD path or script directory path.\n
57+
--------------------------------------------------------------------------------------
58+
Raise an error if no path is provided and neither `cwd` or `base_dir` is true."""
5959
if cwd:
6060
if base_dir:
6161
raise ValueError("Both 'cwd' and 'base_dir' cannot be True at the same time.")
@@ -70,7 +70,8 @@ def _get(path: Optional[str] = None, cwd: bool = False, base_dir: bool = False)
7070

7171
@classmethod
7272
def _persistent(cls, path: str, remove: bool = False) -> None:
73-
"""Add or remove a path from PATH persistently across sessions as well as the current session."""
73+
"""Internal method to add or remove a path from the PATH environment variable,
74+
persistently, across sessions, as well as the current session."""
7475
current_paths = list(cls.paths(as_list=True))
7576
path = _os.path.normpath(path)
7677

src/xulbux/json.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,8 +157,8 @@ def update(
157157

158158
@staticmethod
159159
def _create_nested_path(data_obj: dict, path_keys: list[str], value: Any) -> dict:
160-
"""Creates nested dictionaries/lists based on the given path keys
161-
and sets the specified value at the end of the path."""
160+
"""Internal method that creates nested dictionaries/lists based on the
161+
given path keys and sets the specified value at the end of the path."""
162162
last_idx, current = len(path_keys) - 1, data_obj
163163

164164
for i, key in enumerate(path_keys):

src/xulbux/path.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -179,37 +179,39 @@ def remove(cls, path: str, only_content: bool = False) -> None:
179179
raise Exception(f"Failed to delete {file_path}. Reason: {e}")
180180

181181
@staticmethod
182-
def _expand_env_path(p: str) -> str:
183-
"""Expand environment variables in the given path string."""
184-
if "%" not in p:
185-
return p
182+
def _expand_env_path(path_str: str) -> str:
183+
"""Internal method that expands all environment variables in the given path string."""
184+
if "%" not in path_str:
185+
return path_str
186186

187-
for i in range(1, len(parts := p.split("%")), 2):
187+
for i in range(1, len(parts := path_str.split("%")), 2):
188188
if parts[i].upper() in _os.environ:
189189
parts[i] = _os.environ[parts[i].upper()]
190190

191191
return "".join(parts)
192192

193193
@classmethod
194-
def _find_path(cls, start: str, parts: list[str], use_closest_match: bool) -> Optional[str]:
195-
"""Find a path by traversing the given parts from the start directory,
196-
optionally using closest matches for each part."""
197-
current: str = start
198-
199-
for part in parts:
200-
if _os.path.isfile(current):
201-
return current
202-
if (closest_match := cls._get_closest_match(current, part) if use_closest_match else part) is None:
194+
def _find_path(cls, start_dir: str, path_parts: list[str], use_closest_match: bool) -> Optional[str]:
195+
"""Internal method to find a path by traversing the given parts from
196+
the start directory, optionally using closest matches for each part."""
197+
current_dir: str = start_dir
198+
199+
for part in path_parts:
200+
if _os.path.isfile(current_dir):
201+
return current_dir
202+
if (closest_match := cls._get_closest_match(current_dir, part) if use_closest_match else part) is None:
203203
return None
204-
current = _os.path.join(current, closest_match)
204+
current_dir = _os.path.join(current_dir, closest_match)
205205

206-
return current if _os.path.exists(current) and current != start else None
206+
return current_dir if _os.path.exists(current_dir) and current_dir != start_dir else None
207207

208208
@staticmethod
209-
def _get_closest_match(dir: str, part: str) -> Optional[str]:
210-
"""Get the closest matching file or folder name in the given directory for the given part."""
209+
def _get_closest_match(dir: str, path_part: str) -> Optional[str]:
210+
"""Internal method to get the closest matching file or folder name
211+
in the given directory for the given path part."""
211212
try:
212-
matches = _difflib.get_close_matches(part, _os.listdir(dir), n=1, cutoff=0.6)
213-
return matches[0] if matches else None
213+
return matches[0] if (
214+
matches := _difflib.get_close_matches(path_part, _os.listdir(dir), n=1, cutoff=0.6)
215+
) else None
214216
except Exception:
215217
return None

0 commit comments

Comments
 (0)