Coverage for pyTooling/Common/__init__.py: 91%
166 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-19 06:41 +0000
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-19 06:41 +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.7.3"
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 importlib.resources import files
52from numbers import Number
53from os import chdir
54from pathlib import Path
55from types import ModuleType, TracebackType
56from typing import Type, TypeVar, Callable, Generator, Hashable, List
57from typing import Any, Dict, Tuple, Union, Mapping, Set, Iterable, Optional as Nullable
60try:
61 from pyTooling.Decorators import export
62except ModuleNotFoundError: # pragma: no cover
63 print("[pyTooling.Common] Could not import from 'pyTooling.*'!")
65 try:
66 from Decorators import export
67 except ModuleNotFoundError as ex: # pragma: no cover
68 print("[pyTooling.Common] Could not import directly!")
69 raise ex
72@export
73def getFullyQualifiedName(obj: Any) -> str:
74 """
75 Assemble the fully qualified name of a type.
77 :param obj: The object for with the fully qualified type is to be assembled.
78 :returns: The fully qualified name of obj's type.
79 """
80 try:
81 module = obj.__module__ # for class or function
82 except AttributeError:
83 module = obj.__class__.__module__
85 try:
86 name = obj.__qualname__ # for class or function
87 except AttributeError:
88 name = obj.__class__.__qualname__
90 # If obj is a method of builtin class, then module will be None
91 if module == "builtins" or module is None:
92 return name
94 return f"{module}.{name}"
97@export
98def getResourceFile(module: Union[str, ModuleType], filename: str) -> Path:
99 """
100 Compute the path to a file within a resource package.
102 :param module: The resource package.
103 :param filename: The filename.
104 :returns: Path to the resource's file.
105 :raises ToolingException: If resource file doesn't exist.
106 """
107 # TODO: files() has wrong TypeHint Traversible vs. Path
108 resourcePath: Path = files(module) / filename
109 if not resourcePath.exists():
110 from pyTooling.Exceptions import ToolingException
112 raise ToolingException(f"Resource file '{filename}' not found in resource '{module}'.") \
113 from FileNotFoundError(str(resourcePath))
115 return resourcePath
118@export
119def readResourceFile(module: Union[str, ModuleType], filename: str) -> str:
120 """
121 Read a text file resource from resource package.
123 :param module: The resource package.
124 :param filename: The filename.
125 :returns: File content.
126 """
127 # TODO: check if resource exists.
128 return files(module).joinpath(filename).read_text()
131@export
132def isnestedclass(cls: Type, scope: Type) -> bool:
133 """
134 Returns true, if the given class ``cls`` is a member on an outer class ``scope``.
136 :param cls: Class to check, if it's a nested class.
137 :param scope: Outer class which is the outer scope of ``cls``.
138 :returns: ``True``, if ``cls`` is a nested class within ``scope``.
139 """
140 for mroClass in scope.mro():
141 for memberName in mroClass.__dict__:
142 member = getattr(mroClass, memberName)
143 if isinstance(member, Type):
144 if cls is member:
145 return True
147 return False
150@export
151def getsizeof(obj: Any) -> int:
152 """
153 Recursively calculate the "true" size of an object including complex members like ``__dict__``.
155 :param obj: Object to calculate the size of.
156 :returns: True size of an object in bytes.
158 .. admonition:: Background Information
160 The function :func:`sys.getsizeof` only returns the raw size of a Python object and doesn't account for the
161 overhead of e.g. ``_dict__`` to store dynamically allocated object members.
163 .. seealso::
165 The code is based on code snippets and ideas from:
167 * `Compute Memory Footprint of an Object and its Contents <https://code.activestate.com/recipes/577504/>`__ (MIT Lizense)
168 * `How do I determine the size of an object in Python? <https://stackoverflow.com/a/30316760/3719459>`__ (CC BY-SA 4.0)
169 * `Python __slots__, slots, and object layout <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/080_python_slots>`__ (MIT Lizense)
170 """
171 from sys import getsizeof as sys_getsizeof
173 visitedIDs = set() #: A set to track visited objects, so memory consumption isn't counted multiple times.
175 def recurse(obj: Any) -> int:
176 """
177 Nested function for recursion.
179 :param obj: Subobject to calculate the size of.
180 :returns: Size of a subobject in bytes.
181 """
182 # If already visited, return 0 bytes, so no additional bytes are accumulated
183 objectID = id(obj)
184 if objectID in visitedIDs:
185 return 0
186 else:
187 visitedIDs.add(objectID)
189 # Get objects raw size
190 size: int = sys_getsizeof(obj)
192 # Skip elementary types
193 if isinstance(obj, (str, bytes, bytearray, range, Number)):
194 pass
195 # Handle iterables
196 elif isinstance(obj, (tuple, list, Set, deque)): # TODO: What about builtin "set", "frozenset" and "dict"?
197 for item in obj:
198 size += recurse(item)
199 # Handle mappings
200 elif isinstance(obj, Mapping) or hasattr(obj, 'items'):
201 items = getattr(obj, 'items')
202 # Check if obj.items is a bound method.
203 if hasattr(items, "__self__"):
204 itemView = items()
205 else:
206 itemView = {} # bind(obj, items)
207 for key, value in itemView:
208 size += recurse(key) + recurse(value)
210 # Accumulate members from __dict__
211 if hasattr(obj, '__dict__'):
212 v = vars(obj)
213 size += recurse(v)
215 # Accumulate members from __slots__
216 if hasattr(obj, '__slots__') and obj.__slots__ is not None:
217 for slot in obj.__slots__:
218 if hasattr(obj, slot): 218 ↛ 217line 218 didn't jump to line 217 because the condition on line 218 was always true
219 size += recurse(getattr(obj, slot))
221 return size
223 return recurse(obj)
226def bind(instance, func, methodName: Nullable[str] = None):
227 """
228 Bind the function *func* to *instance*, with either provided name *as_name*
229 or the existing name of *func*. The provided *func* should accept the
230 instance as the first argument, i.e. "self".
232 :param instance:
233 :param func:
234 :param methodName:
235 :return:
236 """
237 if methodName is None:
238 methodName = func.__name__
240 boundMethod = func.__get__(instance, instance.__class__)
241 setattr(instance, methodName, boundMethod)
243 return boundMethod
246@export
247def count(iterator: Iterable) -> int:
248 """
249 Returns the number of elements in an iterable.
251 .. attention:: After counting the iterable's elements, the iterable is consumed.
253 :param iterator: Iterable to consume and count.
254 :return: Number of elements in the iterable.
255 """
256 return len(list(iterator))
259_Element = TypeVar("Element")
262@export
263def firstElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
264 """
265 Returns the first element from an indexable.
267 :param indexable: Indexable to get the first element from.
268 :return: First element.
269 """
270 return indexable[0]
273@export
274def lastElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
275 """
276 Returns the last element from an indexable.
278 :param indexable: Indexable to get the last element from.
279 :return: Last element.
280 """
281 return indexable[-1]
284@export
285def firstItem(iterable: Iterable[_Element]) -> _Element:
286 """
287 Returns the first item from an iterable.
289 :param iterable: Iterable to get the first item from.
290 :return: First item.
291 :raises ValueError: If parameter 'iterable' contains no items.
292 """
293 i = iter(iterable)
294 try:
295 return next(i)
296 except StopIteration:
297 raise ValueError(f"Iterable contains no items.")
300@export
301def lastItem(iterable: Iterable[_Element]) -> _Element:
302 """
303 Returns the last item from an iterable.
305 :param iterable: Iterable to get the last item from.
306 :return: Last item.
307 :raises ValueError: If parameter 'iterable' contains no items.
308 """
309 i = iter(iterable)
310 try:
311 element = next(i)
312 except StopIteration:
313 raise ValueError(f"Iterable contains no items.")
315 for element in i:
316 pass
317 return element
320_DictKey = TypeVar("_DictKey")
321_DictKey1 = TypeVar("_DictKey1")
322_DictKey2 = TypeVar("_DictKey2")
323_DictKey3 = TypeVar("_DictKey3")
324_DictValue1 = TypeVar("_DictValue1")
325_DictValue2 = TypeVar("_DictValue2")
326_DictValue3 = TypeVar("_DictValue3")
329@export
330def firstKey(d: Dict[_DictKey1, _DictValue1]) -> _DictKey1:
331 """
332 Retrieves the first key from a dictionary's keys.
334 :param d: Dictionary to get the first key from.
335 :returns: The first key.
336 :raises ValueError: If parameter 'd' is an empty dictionary.
337 """
338 if len(d) == 0:
339 raise ValueError(f"Dictionary is empty.")
341 return next(iter(d.keys()))
344@export
345def firstValue(d: Dict[_DictKey1, _DictValue1]) -> _DictValue1:
346 """
347 Retrieves the first value from a dictionary's values.
349 :param d: Dictionary to get the first value from.
350 :returns: The first value.
351 :raises ValueError: If parameter 'd' is an empty dictionary.
352 """
353 if len(d) == 0:
354 raise ValueError(f"Dictionary is empty.")
356 return next(iter(d.values()))
359@export
360def firstPair(d: Dict[_DictKey1, _DictValue1]) -> Tuple[_DictKey1, _DictValue1]:
361 """
362 Retrieves the first key-value-pair from a dictionary.
364 :param d: Dictionary to get the first key-value-pair from.
365 :returns: The first key-value-pair as tuple.
366 :raises ValueError: If parameter 'd' is an empty dictionary.
367 """
368 if len(d) == 0:
369 raise ValueError(f"Dictionary is empty.")
371 return next(iter(d.items()))
374@export
375def mergedicts(*dicts: Dict, filter: Nullable[Callable[[Hashable, Any], bool]] = None) -> Dict:
376 """
377 Merge multiple dictionaries into a single new dictionary.
379 If parameter ``filter`` isn't ``None``, then this function is applied to every element during the merge operation. If
380 it returns true, the dictionary element will be present in the resulting dictionary.
382 :param dicts: Tuple of dictionaries to merge as positional parameters.
383 :param filter: Optional filter function to apply to each dictionary element when merging.
384 :returns: A new dictionary containing the merge result.
385 :raises ValueError: If 'mergedicts' got called without any dictionaries parameters.
387 .. seealso::
389 `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>`__
390 """
391 if len(dicts) == 0:
392 raise ValueError(f"Called 'mergedicts' without any dictionary parameter.")
394 if filter is None:
395 return {k: v for d in dicts for k, v in d.items()}
396 else:
397 return {k: v for d in dicts for k, v in d.items() if filter(k, v)}
400@export
401def zipdicts(*dicts: Dict) -> Generator[Tuple, None, None]:
402 """
403 Iterate multiple dictionaries simultaneously.
405 :param dicts: Tuple of dictionaries to iterate as positional parameters.
406 :returns: A generator returning a tuple containing the key and values of each dictionary in the order of
407 given dictionaries.
408 :raises ValueError: If 'zipdicts' got called without any dictionary parameters.
409 :raises ValueError: If not all dictionaries have the same length.
411 .. seealso::
413 The code is based on code snippets and ideas from:
415 * `zipping together Python dicts <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/101_zip_dict>`__ (MIT Lizense)
416 """
417 if len(dicts) == 0:
418 raise ValueError(f"Called 'zipdicts' without any dictionary parameter.")
420 if any(len(d) != len(dicts[0]) for d in dicts):
421 raise ValueError(f"All given dictionaries must have the same length.")
423 def gen(ds: Tuple[Dict, ...]) -> Generator[Tuple, None, None]:
424 for key, item0 in ds[0].items():
425 # WORKAROUND: using redundant parenthesis for Python 3.7 and pypy-3.10
426 yield key, item0, *(d[key] for d in ds[1:])
428 return gen(dicts)
431@export
432class ChangeDirectory:
433 """
434 A context manager for changing a directory.
435 """
436 _oldWorkingDirectory: Path #: Working directory before directory change.
437 _newWorkingDirectory: Path #: New working directory.
439 def __init__(self, directory: Path) -> None:
440 """
441 Initializes the context manager for changing directories.
443 :param directory: The new working directory to change into.
444 """
445 self._newWorkingDirectory = directory
447 def __enter__(self) -> Path:
448 """
449 Enter the context and change the working directory to the parameter given in the class initializer.
451 :returns: The relative path between old and new working directories.
452 """
453 self._oldWorkingDirectory = Path.cwd()
454 chdir(self._newWorkingDirectory)
456 if self._newWorkingDirectory.is_absolute(): 456 ↛ 457line 456 didn't jump to line 457 because the condition on line 456 was never true
457 return self._newWorkingDirectory.resolve()
458 else:
459 return (self._oldWorkingDirectory / self._newWorkingDirectory).resolve()
461 def __exit__(
462 self,
463 exc_type: Nullable[Type[BaseException]] = None,
464 exc_val: Nullable[BaseException] = None,
465 exc_tb: Nullable[TracebackType] = None
466 ) -> Nullable[bool]:
467 """
468 Exit the context and revert any working directory changes.
470 :param exc_type: Exception type
471 :param exc_val: Exception instance
472 :param exc_tb: Exception's traceback.
473 :returns: ``None``
474 """
475 chdir(self._oldWorkingDirectory)