Coverage for pyTooling / Common / __init__.py: 91%
166 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-23 22:21 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-23 22:21 +0000
1# ==================================================================================================================== #
2# _____ _ _ ____ #
3# _ __ _ |_ _|__ ___ | (_)_ __ __ _ / ___|___ _ __ ___ _ __ ___ ___ _ __ #
4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || | / _ \| '_ ` _ \| '_ ` _ \ / _ \| '_ \ #
5# | |_) | |_| || | (_) | (_) | | | | | | (_| || |__| (_) | | | | | | | | | | | (_) | | | | #
6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____\___/|_| |_| |_|_| |_| |_|\___/|_| |_| #
7# |_| |___/ |___/ #
8# ==================================================================================================================== #
9# Authors: #
10# Patrick Lehmann #
11# #
12# License: #
13# ==================================================================================================================== #
14# Copyright 2017-2026 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::
36 See :ref:`high-level help <COMMON>` for explanations and usage examples.
37"""
38__author__ = "Patrick Lehmann"
39__email__ = "Paebbels@gmail.com"
40__copyright__ = "2017-2026, Patrick Lehmann"
41__license__ = "Apache License, Version 2.0"
42__version__ = "8.11.0"
43__keywords__ = [
44 "abstract", "argparse", "attributes", "bfs", "cli", "console", "data structure", "decorators", "dfs",
45 "double linked list", "exceptions", "file system statistics", "generators", "generic library", "generic path",
46 "geometry", "graph", "installation", "iterators", "licensing", "linked list", "message logging", "meta-classes",
47 "overloading", "override", "packaging", "path", "platform", "setuptools", "shapes", "shell", "singleton", "slots",
48 "terminal", "text user interface", "stopwatch", "tree", "TUI", "url", "versioning", "volumes", "warning", "wheel"
49]
50__issue_tracker__ = "https://GitHub.com/pyTooling/pyTooling/issues"
52from collections import deque
53from importlib.resources import files
54from numbers import Number
55from os import chdir
56from pathlib import Path
57from types import ModuleType, TracebackType
58from typing import Type, TypeVar, Callable, Generator, Hashable, List
59from typing import Any, Dict, Tuple, Union, Mapping, Set, Iterable, Optional as Nullable
62try:
63 from pyTooling.Decorators import export
64except ModuleNotFoundError: # pragma: no cover
65 print("[pyTooling.Common] Could not import from 'pyTooling.*'!")
67 try:
68 from Decorators import export
69 except ModuleNotFoundError as ex: # pragma: no cover
70 print("[pyTooling.Common] Could not import directly!")
71 raise ex
74@export
75def getFullyQualifiedName(obj: Any) -> str:
76 """
77 Assemble the fully qualified name of a type.
79 :param obj: The object for with the fully qualified type is to be assembled.
80 :returns: The fully qualified name of obj's type.
81 """
82 try:
83 module = obj.__module__ # for class or function
84 except AttributeError:
85 module = obj.__class__.__module__
87 try:
88 name = obj.__qualname__ # for class or function
89 except AttributeError:
90 name = obj.__class__.__qualname__
92 # If obj is a method of builtin class, then module will be None
93 if module == "builtins" or module is None:
94 return name
96 return f"{module}.{name}"
99@export
100def getResourceFile(module: Union[str, ModuleType], filename: str) -> Path:
101 """
102 Compute the path to a file within a resource package.
104 :param module: The resource package.
105 :param filename: The filename.
106 :returns: Path to the resource's file.
107 :raises ToolingException: If resource file doesn't exist.
108 """
109 # TODO: files() has wrong TypeHint Traversible vs. Path
110 resourcePath: Path = files(module) / filename
111 if not resourcePath.exists():
112 from pyTooling.Exceptions import ToolingException
114 raise ToolingException(f"Resource file '{filename}' not found in resource '{module}'.") \
115 from FileNotFoundError(str(resourcePath))
117 return resourcePath
120@export
121def readResourceFile(module: Union[str, ModuleType], filename: str) -> str:
122 """
123 Read a text file resource from resource package.
125 :param module: The resource package.
126 :param filename: The filename.
127 :returns: File content.
128 """
129 # TODO: check if resource exists.
130 return files(module).joinpath(filename).read_text()
133@export
134def isnestedclass(cls: Type, scope: Type) -> bool:
135 """
136 Returns true, if the given class ``cls`` is a member on an outer class ``scope``.
138 :param cls: Class to check, if it's a nested class.
139 :param scope: Outer class which is the outer scope of ``cls``.
140 :returns: ``True``, if ``cls`` is a nested class within ``scope``.
141 """
142 for mroClass in scope.mro():
143 for memberName in mroClass.__dict__:
144 member = getattr(mroClass, memberName)
145 if isinstance(member, Type):
146 if cls is member:
147 return True
149 return False
152@export
153def getsizeof(obj: Any) -> int:
154 """
155 Recursively calculate the "true" size of an object including complex members like ``__dict__``.
157 :param obj: Object to calculate the size of.
158 :returns: True size of an object in bytes.
160 .. admonition:: Background Information
162 The function :func:`sys.getsizeof` only returns the raw size of a Python object and doesn't account for the
163 overhead of e.g. ``_dict__`` to store dynamically allocated object members.
165 .. seealso::
167 The code is based on code snippets and ideas from:
169 * `Compute Memory Footprint of an Object and its Contents <https://code.activestate.com/recipes/577504/>`__ (MIT Lizense)
170 * `How do I determine the size of an object in Python? <https://stackoverflow.com/a/30316760/3719459>`__ (CC BY-SA 4.0)
171 * `Python __slots__, slots, and object layout <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/080_python_slots>`__ (MIT Lizense)
172 """
173 from sys import getsizeof as sys_getsizeof
175 visitedIDs = set() #: A set to track visited objects, so memory consumption isn't counted multiple times.
177 def recurse(obj: Any) -> int:
178 """
179 Nested function for recursion.
181 :param obj: Subobject to calculate the size of.
182 :returns: Size of a subobject in bytes.
183 """
184 # If already visited, return 0 bytes, so no additional bytes are accumulated
185 objectID = id(obj)
186 if objectID in visitedIDs:
187 return 0
188 else:
189 visitedIDs.add(objectID)
191 # Get objects raw size
192 size: int = sys_getsizeof(obj)
194 # Skip elementary types
195 if isinstance(obj, (str, bytes, bytearray, range, Number)):
196 pass
197 # Handle iterables
198 elif isinstance(obj, (tuple, list, Set, deque)): # TODO: What about builtin "set", "frozenset" and "dict"?
199 for item in obj:
200 size += recurse(item)
201 # Handle mappings
202 elif isinstance(obj, Mapping) or hasattr(obj, 'items'):
203 items = getattr(obj, 'items')
204 # Check if obj.items is a bound method.
205 if hasattr(items, "__self__"):
206 itemView = items()
207 else:
208 itemView = {} # bind(obj, items)
209 for key, value in itemView:
210 size += recurse(key) + recurse(value)
212 # Accumulate members from __dict__
213 if hasattr(obj, '__dict__'):
214 v = vars(obj)
215 size += recurse(v)
217 # Accumulate members from __slots__
218 if hasattr(obj, '__slots__') and obj.__slots__ is not None:
219 for slot in obj.__slots__:
220 if hasattr(obj, slot): 220 ↛ 219line 220 didn't jump to line 219 because the condition on line 220 was always true
221 size += recurse(getattr(obj, slot))
223 return size
225 return recurse(obj)
228def bind(instance, func, methodName: Nullable[str] = None):
229 """
230 Bind the function *func* to *instance*, with either provided name *as_name*
231 or the existing name of *func*. The provided *func* should accept the
232 instance as the first argument, i.e. "self".
234 :param instance:
235 :param func:
236 :param methodName:
237 :return:
238 """
239 if methodName is None:
240 methodName = func.__name__
242 boundMethod = func.__get__(instance, instance.__class__)
243 setattr(instance, methodName, boundMethod)
245 return boundMethod
248@export
249def count(iterator: Iterable) -> int:
250 """
251 Returns the number of elements in an iterable.
253 .. attention:: After counting the iterable's elements, the iterable is consumed.
255 :param iterator: Iterable to consume and count.
256 :return: Number of elements in the iterable.
257 """
258 return len(list(iterator))
261_Element = TypeVar("Element")
264@export
265def firstElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
266 """
267 Returns the first element from an indexable.
269 :param indexable: Indexable to get the first element from.
270 :return: First element.
271 """
272 return indexable[0]
275@export
276def lastElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
277 """
278 Returns the last element from an indexable.
280 :param indexable: Indexable to get the last element from.
281 :return: Last element.
282 """
283 return indexable[-1]
286@export
287def firstItem(iterable: Iterable[_Element]) -> _Element:
288 """
289 Returns the first item from an iterable.
291 :param iterable: Iterable to get the first item from.
292 :return: First item.
293 :raises ValueError: If parameter 'iterable' contains no items.
294 """
295 i = iter(iterable)
296 try:
297 return next(i)
298 except StopIteration:
299 raise ValueError(f"Iterable contains no items.")
302@export
303def lastItem(iterable: Iterable[_Element]) -> _Element:
304 """
305 Returns the last item from an iterable.
307 :param iterable: Iterable to get the last item from.
308 :return: Last item.
309 :raises ValueError: If parameter 'iterable' contains no items.
310 """
311 i = iter(iterable)
312 try:
313 element = next(i)
314 except StopIteration:
315 raise ValueError(f"Iterable contains no items.")
317 for element in i:
318 pass
319 return element
322_DictKey = TypeVar("_DictKey")
323_DictKey1 = TypeVar("_DictKey1")
324_DictKey2 = TypeVar("_DictKey2")
325_DictKey3 = TypeVar("_DictKey3")
326_DictValue1 = TypeVar("_DictValue1")
327_DictValue2 = TypeVar("_DictValue2")
328_DictValue3 = TypeVar("_DictValue3")
331@export
332def firstKey(d: Dict[_DictKey1, _DictValue1]) -> _DictKey1:
333 """
334 Retrieves the first key from a dictionary's keys.
336 :param d: Dictionary to get the first key from.
337 :returns: The first key.
338 :raises ValueError: If parameter 'd' is an empty dictionary.
339 """
340 if len(d) == 0:
341 raise ValueError(f"Dictionary is empty.")
343 return next(iter(d.keys()))
346@export
347def firstValue(d: Dict[_DictKey1, _DictValue1]) -> _DictValue1:
348 """
349 Retrieves the first value from a dictionary's values.
351 :param d: Dictionary to get the first value from.
352 :returns: The first value.
353 :raises ValueError: If parameter 'd' is an empty dictionary.
354 """
355 if len(d) == 0:
356 raise ValueError(f"Dictionary is empty.")
358 return next(iter(d.values()))
361@export
362def firstPair(d: Dict[_DictKey1, _DictValue1]) -> Tuple[_DictKey1, _DictValue1]:
363 """
364 Retrieves the first key-value-pair from a dictionary.
366 :param d: Dictionary to get the first key-value-pair from.
367 :returns: The first key-value-pair as tuple.
368 :raises ValueError: If parameter 'd' is an empty dictionary.
369 """
370 if len(d) == 0:
371 raise ValueError(f"Dictionary is empty.")
373 return next(iter(d.items()))
376@export
377def mergedicts(*dicts: Dict, filter: Nullable[Callable[[Hashable, Any], bool]] = None) -> Dict:
378 """
379 Merge multiple dictionaries into a single new dictionary.
381 If parameter ``filter`` isn't ``None``, then this function is applied to every element during the merge operation. If
382 it returns true, the dictionary element will be present in the resulting dictionary.
384 :param dicts: Tuple of dictionaries to merge as positional parameters.
385 :param filter: Optional filter function to apply to each dictionary element when merging.
386 :returns: A new dictionary containing the merge result.
387 :raises ValueError: If 'mergedicts' got called without any dictionaries parameters.
389 .. seealso::
391 `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>`__
392 """
393 if len(dicts) == 0:
394 raise ValueError(f"Called 'mergedicts' without any dictionary parameter.")
396 if filter is None:
397 return {k: v for d in dicts for k, v in d.items()}
398 else:
399 return {k: v for d in dicts for k, v in d.items() if filter(k, v)}
402@export
403def zipdicts(*dicts: Dict) -> Generator[Tuple, None, None]:
404 """
405 Iterate multiple dictionaries simultaneously.
407 :param dicts: Tuple of dictionaries to iterate as positional parameters.
408 :returns: A generator returning a tuple containing the key and values of each dictionary in the order of
409 given dictionaries.
410 :raises ValueError: If 'zipdicts' got called without any dictionary parameters.
411 :raises ValueError: If not all dictionaries have the same length.
413 .. seealso::
415 The code is based on code snippets and ideas from:
417 * `zipping together Python dicts <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/101_zip_dict>`__ (MIT Lizense)
418 """
419 if len(dicts) == 0:
420 raise ValueError(f"Called 'zipdicts' without any dictionary parameter.")
422 if any(len(d) != len(dicts[0]) for d in dicts):
423 raise ValueError(f"All given dictionaries must have the same length.")
425 def gen(ds: Tuple[Dict, ...]) -> Generator[Tuple, None, None]:
426 for key, item0 in ds[0].items():
427 # WORKAROUND: using redundant parenthesis for Python 3.7 and pypy-3.10
428 yield key, item0, *(d[key] for d in ds[1:])
430 return gen(dicts)
433@export
434class ChangeDirectory:
435 """
436 A context manager for changing a directory.
437 """
438 _oldWorkingDirectory: Path #: Working directory before directory change.
439 _newWorkingDirectory: Path #: New working directory.
441 def __init__(self, directory: Path) -> None:
442 """
443 Initializes the context manager for changing directories.
445 :param directory: The new working directory to change into.
446 """
447 self._newWorkingDirectory = directory
449 def __enter__(self) -> Path:
450 """
451 Enter the context and change the working directory to the parameter given in the class initializer.
453 :returns: The relative path between old and new working directories.
454 """
455 self._oldWorkingDirectory = Path.cwd()
456 chdir(self._newWorkingDirectory)
458 if self._newWorkingDirectory.is_absolute(): 458 ↛ 459line 458 didn't jump to line 459 because the condition on line 458 was never true
459 return self._newWorkingDirectory.resolve()
460 else:
461 return (self._oldWorkingDirectory / self._newWorkingDirectory).resolve()
463 def __exit__(
464 self,
465 exc_type: Nullable[Type[BaseException]] = None,
466 exc_val: Nullable[BaseException] = None,
467 exc_tb: Nullable[TracebackType] = None
468 ) -> Nullable[bool]:
469 """
470 Exit the context and revert any working directory changes.
472 :param exc_type: Exception type
473 :param exc_val: Exception instance
474 :param exc_tb: Exception's traceback.
475 :returns: ``None``
476 """
477 chdir(self._oldWorkingDirectory)