Coverage for pyTooling/Common/__init__.py: 91%
179 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-18 22:20 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-18 22:20 +0000
1# ==================================================================================================================== #
2# _____ _ _ ____ #
3# _ __ _ |_ _|__ ___ | (_)_ __ __ _ / ___|___ _ __ ___ _ __ ___ ___ _ __ #
4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || | / _ \| '_ ` _ \| '_ ` _ \ / _ \| '_ \ #
5# | |_) | |_| || | (_) | (_) | | | | | | (_| || |__| (_) | | | | | | | | | | | (_) | | | | #
6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____\___/|_| |_| |_|_| |_| |_|\___/|_| |_| #
7# |_| |___/ |___/ #
8# ==================================================================================================================== #
9# Authors: #
10# Patrick Lehmann #
11# #
12# License: #
13# ==================================================================================================================== #
14# Copyright 2017-2025 Patrick Lehmann - Bötzingen, Germany #
15# #
16# Licensed under the Apache License, Version 2.0 (the "License"); #
17# you may not use this file except in compliance with the License. #
18# You may obtain a copy of the License at #
19# #
20# http://www.apache.org/licenses/LICENSE-2.0 #
21# #
22# Unless required by applicable law or agreed to in writing, software #
23# distributed under the License is distributed on an "AS IS" BASIS, #
24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
25# See the License for the specific language governing permissions and #
26# limitations under the License. #
27# #
28# SPDX-License-Identifier: Apache-2.0 #
29# ==================================================================================================================== #
30#
31"""
32Common types, helper functions and classes.
34.. hint:: See :ref:`high-level help <COMMON>` for explanations and usage examples.
35"""
36__author__ = "Patrick Lehmann"
37__email__ = "Paebbels@gmail.com"
38__copyright__ = "2017-2025, Patrick Lehmann"
39__license__ = "Apache License, Version 2.0"
40__version__ = "8.4.7"
41__keywords__ = [
42 "abstract", "argparse", "attributes", "bfs", "cli", "console", "data structure", "decorators", "dfs",
43 "double linked list", "exceptions", "file system statistics", "generators", "generic library", "generic path",
44 "geometry", "graph", "installation", "iterators", "licensing", "linked list", "message logging", "meta-classes",
45 "overloading", "override", "packaging", "path", "platform", "setuptools", "shapes", "shell", "singleton", "slots",
46 "terminal", "text user interface", "stopwatch", "tree", "TUI", "url", "versioning", "volumes", "wheel"
47]
48__issue_tracker__ = "https://GitHub.com/pyTooling/pyTooling/issues"
50from collections import deque
51from numbers import Number
52from os import chdir
53from pathlib import Path
54from types import ModuleType, TracebackType
55from typing import Type, TypeVar, Callable, Generator, overload, Hashable, Optional, List
56from typing import Any, Dict, Tuple, Union, Mapping, Set, Iterable, Optional as Nullable
59try:
60 from pyTooling.Decorators import export
61except ModuleNotFoundError: # pragma: no cover
62 print("[pyTooling.Common] Could not import from 'pyTooling.*'!")
64 try:
65 from Decorators import export
66 except ModuleNotFoundError as ex: # pragma: no cover
67 print("[pyTooling.Common] Could not import directly!")
68 raise ex
71@export
72def getFullyQualifiedName(obj: Any):
73 try:
74 module = obj.__module__ # for class or function
75 except AttributeError:
76 module = obj.__class__.__module__
78 try:
79 name = obj.__qualname__ # for class or function
80 except AttributeError:
81 name = obj.__class__.__qualname__
83 # If obj is a method of builtin class, then module will be None
84 if module == "builtins" or module is None:
85 return name
87 return f"{module}.{name}"
90@export
91def getResourceFile(module: Union[str, ModuleType], filename: str) -> Path:
92 from importlib.resources import files # TODO: can be used as regular import > 3.8
94 # TODO: files() has wrong TypeHint Traversible vs. Path
95 resourcePath: Path = files(module) / filename
96 if not resourcePath.exists():
97 from pyTooling.Exceptions import ToolingException
99 raise ToolingException(f"Resource file '{filename}' not found in resource '{module}'.") from FileNotFoundError(str(resourcePath))
101 return resourcePath
104@export
105def readResourceFile(module: Union[str, ModuleType], filename: str) -> str:
106 from importlib.resources import files
108 return files(module).joinpath(filename).read_text()
111@export
112def isnestedclass(cls: Type, scope: Type) -> bool:
113 """
114 Returns true, if the given class ``cls`` is a member on an outer class ``scope``.
116 :param cls: Class to check, if it's a nested class.
117 :param scope: Outer class which is the outer scope of ``cls``.
118 :returns: ``True``, if ``cls`` is a nested class within ``scope``.
119 """
120 for mroClass in scope.mro():
121 for memberName in mroClass.__dict__:
122 member = getattr(mroClass, memberName)
123 if isinstance(member, Type):
124 if cls is member:
125 return True
127 return False
130@export
131def getsizeof(obj: Any) -> int:
132 """
133 Recursively calculate the "true" size of an object including complex members like ``__dict__``.
135 :param obj: Object to calculate the size of.
136 :returns: True size of an object in bytes.
138 .. admonition:: Background Information
140 The function :func:`sys.getsizeof` only returns the raw size of a Python object and doesn't account for the
141 overhead of e.g. ``_dict__`` to store dynamically allocated object members.
143 .. seealso::
145 The code is based on code snippets and ideas from:
147 * `Compute Memory Footprint of an Object and its Contents <https://code.activestate.com/recipes/577504/>`__ (MIT Lizense)
148 * `How do I determine the size of an object in Python? <https://stackoverflow.com/a/30316760/3719459>`__ (CC BY-SA 4.0)
149 * `Python __slots__, slots, and object layout <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/080_python_slots>`__ (MIT Lizense)
150 """
151 from sys import getsizeof as sys_getsizeof
153 visitedIDs = set() #: A set to track visited objects, so memory consumption isn't counted multiple times.
155 def recurse(obj: Any) -> int:
156 """
157 Nested function for recursion.
159 :param obj: Subobject to calculate the size of.
160 :returns: Size of a subobject in bytes.
161 """
162 # If already visited, return 0 bytes, so no additional bytes are accumulated
163 objectID = id(obj)
164 if objectID in visitedIDs:
165 return 0
166 else:
167 visitedIDs.add(objectID)
169 # Get objects raw size
170 size: int = sys_getsizeof(obj)
172 # Skip elementary types
173 if isinstance(obj, (str, bytes, bytearray, range, Number)):
174 pass
175 # Handle iterables
176 elif isinstance(obj, (tuple, list, Set, deque)): # TODO: What about builtin "set", "frozenset" and "dict"?
177 for item in obj:
178 size += recurse(item)
179 # Handle mappings
180 elif isinstance(obj, Mapping) or hasattr(obj, 'items'):
181 items = getattr(obj, 'items')
182 # Check if obj.items is a bound method.
183 if hasattr(items, "__self__"):
184 itemView = items()
185 else:
186 itemView = {} # bind(obj, items)
187 for key, value in itemView:
188 size += recurse(key) + recurse(value)
190 # Accumulate members from __dict__
191 if hasattr(obj, '__dict__'):
192 v = vars(obj)
193 size += recurse(v)
195 # Accumulate members from __slots__
196 if hasattr(obj, '__slots__') and obj.__slots__ is not None:
197 for slot in obj.__slots__:
198 if hasattr(obj, slot): 198 ↛ 197line 198 didn't jump to line 197 because the condition on line 198 was always true
199 size += recurse(getattr(obj, slot))
201 return size
203 return recurse(obj)
206def bind(instance, func, methodName: Nullable[str] = None):
207 """
208 Bind the function *func* to *instance*, with either provided name *as_name*
209 or the existing name of *func*. The provided *func* should accept the
210 instance as the first argument, i.e. "self".
212 :param instance:
213 :param func:
214 :param methodName:
215 :return:
216 """
217 if methodName is None:
218 methodName = func.__name__
220 boundMethod = func.__get__(instance, instance.__class__)
221 setattr(instance, methodName, boundMethod)
223 return boundMethod
226@export
227def count(iterator: Iterable) -> int:
228 """
229 Returns the number of elements in an iterable.
231 .. attention:: After counting the iterable's elements, the iterable is consumed.
233 :param iterator: Iterable to consume and count.
234 :return: Number of elements in the iterable.
235 """
236 return len(list(iterator))
239_Element = TypeVar("Element")
242@export
243def firstElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
244 """
245 Returns the first element from an indexable.
247 :param indexable: Indexable to get the first element from.
248 :return: First element.
249 """
250 return indexable[0]
253@export
254def lastElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
255 """
256 Returns the last element from an indexable.
258 :param indexable: Indexable to get the last element from.
259 :return: Last element.
260 """
261 return indexable[-1]
264@export
265def firstItem(iterable: Iterable[_Element]) -> _Element:
266 """
267 Returns the first item from an iterable.
269 :param iterable: Iterable to get the first item from.
270 :return: First item.
271 :raises ValueError: If parameter 'iterable' contains no items.
272 """
273 i = iter(iterable)
274 try:
275 return next(i)
276 except StopIteration:
277 raise ValueError(f"Iterable contains no items.")
280@export
281def lastItem(iterable: Iterable[_Element]) -> _Element:
282 """
283 Returns the last item from an iterable.
285 :param iterable: Iterable to get the last item from.
286 :return: Last item.
287 :raises ValueError: If parameter 'iterable' contains no items.
288 """
289 i = iter(iterable)
290 try:
291 element = next(i)
292 except StopIteration:
293 raise ValueError(f"Iterable contains no items.")
295 for element in i:
296 pass
297 return element
300_DictKey = TypeVar("_DictKey")
301_DictKey1 = TypeVar("_DictKey1")
302_DictKey2 = TypeVar("_DictKey2")
303_DictKey3 = TypeVar("_DictKey3")
304_DictValue1 = TypeVar("_DictValue1")
305_DictValue2 = TypeVar("_DictValue2")
306_DictValue3 = TypeVar("_DictValue3")
309@export
310def firstKey(d: Dict[_DictKey1, _DictValue1]) -> _DictKey1:
311 """
312 Retrieves the first key from a dictionary's keys.
314 :param d: Dictionary to get the first key from.
315 :returns: The first key.
316 :raises ValueError: If parameter 'd' is an empty dictionary.
317 """
318 if len(d) == 0:
319 raise ValueError(f"Dictionary is empty.")
321 return next(iter(d.keys()))
324@export
325def firstValue(d: Dict[_DictKey1, _DictValue1]) -> _DictValue1:
326 """
327 Retrieves the first value from a dictionary's values.
329 :param d: Dictionary to get the first value from.
330 :returns: The first value.
331 :raises ValueError: If parameter 'd' is an empty dictionary.
332 """
333 if len(d) == 0:
334 raise ValueError(f"Dictionary is empty.")
336 return next(iter(d.values()))
339@export
340def firstPair(d: Dict[_DictKey1, _DictValue1]) -> Tuple[_DictKey1, _DictValue1]:
341 """
342 Retrieves the first key-value-pair from a dictionary.
344 :param d: Dictionary to get the first key-value-pair from.
345 :returns: The first key-value-pair as tuple.
346 :raises ValueError: If parameter 'd' is an empty dictionary.
347 """
348 if len(d) == 0:
349 raise ValueError(f"Dictionary is empty.")
351 return next(iter(d.items()))
354@overload
355def mergedicts(
356 m1: Mapping[_DictKey1, _DictValue1],
357 filter: Optional[Callable[[Hashable, Any], bool]]
358) -> Dict[Union[_DictKey1], Union[_DictValue1]]:
359#) -> Generator[Tuple[Union[_DictKey1], Union[_DictValue1]], None, None]:
360 ... # pragma: no cover
363@overload
364def mergedicts(
365 m1: Mapping[_DictKey1, _DictValue1],
366 m2: Mapping[_DictKey2, _DictValue2],
367 filter: Optional[Callable[[Hashable, Any], bool]]
368) -> Dict[Union[_DictKey1, _DictKey2], Union[_DictValue1, _DictValue2]]:
369# ) -> Generator[Tuple[Union[_DictKey1, _DictKey2], Union[_DictValue1, _DictValue2]], None, None]:
370 ... # pragma: no cover
373@overload
374def mergedicts(
375 m1: Mapping[_DictKey1, _DictValue1],
376 m2: Mapping[_DictKey2, _DictValue2],
377 m3: Mapping[_DictKey3, _DictValue3],
378 filter: Optional[Callable[[Hashable, Any], bool]]
379) -> Dict[Union[_DictKey1, _DictKey2, _DictKey3], Union[_DictValue1, _DictValue2, _DictValue3]]:
380#) -> Generator[Tuple[Union[_DictKey1, _DictKey2, _DictKey3], Union[_DictValue1, _DictValue2, _DictValue3]], None, None]:
381 ... # pragma: no cover
384@export
385def mergedicts(*dicts: Tuple[Dict, ...], filter: Nullable[Callable[[Hashable, Any], bool]] = None) -> Dict:
386 """
387 Merge multiple dictionaries into a single new dictionary.
389 If parameter ``filter`` isn't ``None``, then this function is applied to every element during the merge operation. If
390 it returns true, the dictionary element will be present in the resulting dictionary.
392 :param dicts: Tuple of dictionaries to merge as positional parameters.
393 :param filter: Optional filter function to apply to each dictionary element when merging.
394 :returns: A new dictionary containing the merge result.
395 :raises ValueError: If 'mergedicts' got called without any dictionaries parameters.
397 .. seealso::
399 `How do I merge two dictionaries in a single expression in Python? <https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python>`__
400 """
401 if len(dicts) == 0:
402 raise ValueError(f"Called 'mergedicts' without any dictionary parameter.")
404 if filter is None:
405 return {k: v for d in dicts for k, v in d.items()}
406 else:
407 return {k: v for d in dicts for k, v in d.items() if filter(k, v)}
410@overload
411def zipdicts(
412 m1: Mapping[_DictKey, _DictValue1]
413) -> Generator[Tuple[_DictKey, _DictValue1], None, None]:
414 ... # pragma: no cover
417@overload
418def zipdicts(
419 m1: Mapping[_DictKey, _DictValue1],
420 m2: Mapping[_DictKey, _DictValue2]
421) -> Generator[Tuple[_DictKey, _DictValue1, _DictValue2], None, None]:
422 ... # pragma: no cover
425@overload
426def zipdicts(
427 m1: Mapping[_DictKey, _DictValue1],
428 m2: Mapping[_DictKey, _DictValue2],
429 m3: Mapping[_DictKey, _DictValue3]
430) -> Generator[Tuple[_DictKey, _DictValue1, _DictValue2, _DictValue3], None, None]:
431 ... # pragma: no cover
434@export
435def zipdicts(*dicts: Tuple[Dict, ...]) -> Generator[Tuple, None, None]:
436 """
437 Iterate multiple dictionaries simultaneously.
439 :param dicts: Tuple of dictionaries to iterate as positional parameters.
440 :returns: A generator returning a tuple containing the key and values of each dictionary in the order of
441 given dictionaries.
442 :raises ValueError: If 'zipdicts' got called without any dictionary parameters.
443 :raises ValueError: If not all dictionaries have the same length.
445 .. seealso::
447 The code is based on code snippets and ideas from:
449 * `zipping together Python dicts <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/101_zip_dict>`__ (MIT Lizense)
450 """
451 if len(dicts) == 0:
452 raise ValueError(f"Called 'zipdicts' without any dictionary parameter.")
454 if any(len(d) != len(dicts[0]) for d in dicts):
455 raise ValueError(f"All given dictionaries must have the same length.")
457 def gen(ds: Tuple[Dict, ...]) -> Generator[Tuple, None, None]:
458 for key, item0 in ds[0].items():
459 # WORKAROUND: using redundant parenthesis for Python 3.7 and pypy-3.10
460 yield key, item0, *(d[key] for d in ds[1:])
462 return gen(dicts)
465@export
466class ChangeDirectory:
467 _oldWorkingDirectory: Path
468 _newWorkingDirectory: Path
470 def __init__(self, directory: Path) -> None:
471 self._newWorkingDirectory = directory
473 def __enter__(self) -> Path:
474 self._oldWorkingDirectory = Path.cwd()
475 chdir(self._newWorkingDirectory)
477 if self._newWorkingDirectory.is_absolute(): 477 ↛ 478line 477 didn't jump to line 478 because the condition on line 477 was never true
478 return self._newWorkingDirectory.resolve()
479 else:
480 return (self._oldWorkingDirectory / self._newWorkingDirectory).resolve()
482 def __exit__(
483 self,
484 exc_type: Nullable[Type[BaseException]] = None,
485 exc_val: Nullable[BaseException] = None,
486 exc_tb: Nullable[TracebackType] = None
487 ) -> Nullable[bool]:
488 chdir(self._oldWorkingDirectory)