Coverage for pyTooling/Common/__init__.py: 91%
164 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-25 22:22 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-25 22:22 +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.1"
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 pathlib import Path
53from types import ModuleType
54from typing import Type, TypeVar, Callable, Generator, overload, Hashable, Optional, List
55from typing import Any, Dict, Tuple, Union, Mapping, Set, Iterable, Optional as Nullable
58try:
59 from pyTooling.Decorators import export
60except ModuleNotFoundError: # pragma: no cover
61 print("[pyTooling.Common] Could not import from 'pyTooling.*'!")
63 try:
64 from Decorators import export
65 except ModuleNotFoundError as ex: # pragma: no cover
66 print("[pyTooling.Common] Could not import directly!")
67 raise ex
70@export
71def getFullyQualifiedName(obj: Any):
72 try:
73 module = obj.__module__ # for class or function
74 except AttributeError:
75 module = obj.__class__.__module__
77 try:
78 name = obj.__qualname__ # for class or function
79 except AttributeError:
80 name = obj.__class__.__qualname__
82 # If obj is a method of builtin class, then module will be None
83 if module == "builtins" or module is None:
84 return name
86 return f"{module}.{name}"
89@export
90def getResourceFile(module: Union[str, ModuleType], filename: str) -> Path:
91 from importlib.resources import files # TODO: can be used as regular import > 3.8
93 # TODO: files() has wrong TypeHint Traversible vs. Path
94 resourcePath: Path = files(module) / filename
95 if not resourcePath.exists():
96 from pyTooling.Exceptions import ToolingException
98 raise ToolingException(f"Resource file '{filename}' not found in resource '{module}'.") from FileNotFoundError(str(resourcePath))
100 return resourcePath
103@export
104def readResourceFile(module: Union[str, ModuleType], filename: str) -> str:
105 from importlib.resources import files
107 return files(module).joinpath(filename).read_text()
110@export
111def isnestedclass(cls: Type, scope: Type) -> bool:
112 """
113 Returns true, if the given class ``cls`` is a member on an outer class ``scope``.
115 :param cls: Class to check, if it's a nested class.
116 :param scope: Outer class which is the outer scope of ``cls``.
117 :returns: ``True``, if ``cls`` is a nested class within ``scope``.
118 """
119 for mroClass in scope.mro():
120 for memberName in mroClass.__dict__:
121 member = getattr(mroClass, memberName)
122 if isinstance(member, Type):
123 if cls is member:
124 return True
126 return False
129@export
130def getsizeof(obj: Any) -> int:
131 """
132 Recursively calculate the "true" size of an object including complex members like ``__dict__``.
134 :param obj: Object to calculate the size of.
135 :returns: True size of an object in bytes.
137 .. admonition:: Background Information
139 The function :func:`sys.getsizeof` only returns the raw size of a Python object and doesn't account for the
140 overhead of e.g. ``_dict__`` to store dynamically allocated object members.
142 .. seealso::
144 The code is based on code snippets and ideas from:
146 * `Compute Memory Footprint of an Object and its Contents <https://code.activestate.com/recipes/577504/>`__ (MIT Lizense)
147 * `How do I determine the size of an object in Python? <https://stackoverflow.com/a/30316760/3719459>`__ (CC BY-SA 4.0)
148 * `Python __slots__, slots, and object layout <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/080_python_slots>`__ (MIT Lizense)
149 """
150 from sys import getsizeof as sys_getsizeof
152 visitedIDs = set() #: A set to track visited objects, so memory consumption isn't counted multiple times.
154 def recurse(obj: Any) -> int:
155 """
156 Nested function for recursion.
158 :param obj: Subobject to calculate the size of.
159 :returns: Size of a subobject in bytes.
160 """
161 # If already visited, return 0 bytes, so no additional bytes are accumulated
162 objectID = id(obj)
163 if objectID in visitedIDs:
164 return 0
165 else:
166 visitedIDs.add(objectID)
168 # Get objects raw size
169 size: int = sys_getsizeof(obj)
171 # Skip elementary types
172 if isinstance(obj, (str, bytes, bytearray, range, Number)):
173 pass
174 # Handle iterables
175 elif isinstance(obj, (tuple, list, Set, deque)): # TODO: What about builtin "set", "frozenset" and "dict"?
176 for item in obj:
177 size += recurse(item)
178 # Handle mappings
179 elif isinstance(obj, Mapping) or hasattr(obj, 'items'):
180 items = getattr(obj, 'items')
181 # Check if obj.items is a bound method.
182 if hasattr(items, "__self__"):
183 itemView = items()
184 else:
185 itemView = {} # bind(obj, items)
186 for key, value in itemView:
187 size += recurse(key) + recurse(value)
189 # Accumulate members from __dict__
190 if hasattr(obj, '__dict__'):
191 v = vars(obj)
192 size += recurse(v)
194 # Accumulate members from __slots__
195 if hasattr(obj, '__slots__') and obj.__slots__ is not None:
196 for slot in obj.__slots__:
197 if hasattr(obj, slot): 197 ↛ 196line 197 didn't jump to line 196 because the condition on line 197 was always true
198 size += recurse(getattr(obj, slot))
200 return size
202 return recurse(obj)
205def bind(instance, func, methodName: Nullable[str] = None):
206 """
207 Bind the function *func* to *instance*, with either provided name *as_name*
208 or the existing name of *func*. The provided *func* should accept the
209 instance as the first argument, i.e. "self".
211 :param instance:
212 :param func:
213 :param methodName:
214 :return:
215 """
216 if methodName is None:
217 methodName = func.__name__
219 boundMethod = func.__get__(instance, instance.__class__)
220 setattr(instance, methodName, boundMethod)
222 return boundMethod
225@export
226def count(iterator: Iterable) -> int:
227 """
228 Returns the number of elements in an iterable.
230 .. attention:: After counting the iterable's elements, the iterable is consumed.
232 :param iterator: Iterable to consume and count.
233 :return: Number of elements in the iterable.
234 """
235 return len(list(iterator))
238_Element = TypeVar("Element")
241@export
242def firstElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
243 """
244 Returns the first element from an indexable.
246 :param indexable: Indexable to get the first element from.
247 :return: First element.
248 """
249 return indexable[0]
252@export
253def lastElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
254 """
255 Returns the last element from an indexable.
257 :param indexable: Indexable to get the last element from.
258 :return: Last element.
259 """
260 return indexable[-1]
263@export
264def firstItem(iterable: Iterable[_Element]) -> _Element:
265 """
266 Returns the first item from an iterable.
268 :param iterable: Iterable to get the first item from.
269 :return: First item.
270 :raises ValueError: If parameter 'iterable' contains no items.
271 """
272 i = iter(iterable)
273 try:
274 return next(i)
275 except StopIteration:
276 raise ValueError(f"Iterable contains no items.")
279@export
280def lastItem(iterable: Iterable[_Element]) -> _Element:
281 """
282 Returns the last item from an iterable.
284 :param iterable: Iterable to get the last item from.
285 :return: Last item.
286 :raises ValueError: If parameter 'iterable' contains no items.
287 """
288 i = iter(iterable)
289 try:
290 element = next(i)
291 except StopIteration:
292 raise ValueError(f"Iterable contains no items.")
294 for element in i:
295 pass
296 return element
299_DictKey = TypeVar("_DictKey")
300_DictKey1 = TypeVar("_DictKey1")
301_DictKey2 = TypeVar("_DictKey2")
302_DictKey3 = TypeVar("_DictKey3")
303_DictValue1 = TypeVar("_DictValue1")
304_DictValue2 = TypeVar("_DictValue2")
305_DictValue3 = TypeVar("_DictValue3")
308@export
309def firstKey(d: Dict[_DictKey1, _DictValue1]) -> _DictKey1:
310 """
311 Retrieves the first key from a dictionary's keys.
313 :param d: Dictionary to get the first key from.
314 :returns: The first key.
315 :raises ValueError: If parameter 'd' is an empty dictionary.
316 """
317 if len(d) == 0:
318 raise ValueError(f"Dictionary is empty.")
320 return next(iter(d.keys()))
323@export
324def firstValue(d: Dict[_DictKey1, _DictValue1]) -> _DictValue1:
325 """
326 Retrieves the first value from a dictionary's values.
328 :param d: Dictionary to get the first value from.
329 :returns: The first value.
330 :raises ValueError: If parameter 'd' is an empty dictionary.
331 """
332 if len(d) == 0:
333 raise ValueError(f"Dictionary is empty.")
335 return next(iter(d.values()))
338@export
339def firstPair(d: Dict[_DictKey1, _DictValue1]) -> Tuple[_DictKey1, _DictValue1]:
340 """
341 Retrieves the first key-value-pair from a dictionary.
343 :param d: Dictionary to get the first key-value-pair from.
344 :returns: The first key-value-pair as tuple.
345 :raises ValueError: If parameter 'd' is an empty dictionary.
346 """
347 if len(d) == 0:
348 raise ValueError(f"Dictionary is empty.")
350 return next(iter(d.items()))
353@overload
354def mergedicts(
355 m1: Mapping[_DictKey1, _DictValue1],
356 filter: Optional[Callable[[Hashable, Any], bool]]
357) -> Dict[Union[_DictKey1], Union[_DictValue1]]:
358#) -> Generator[Tuple[Union[_DictKey1], Union[_DictValue1]], None, None]:
359 ... # pragma: no cover
362@overload
363def mergedicts(
364 m1: Mapping[_DictKey1, _DictValue1],
365 m2: Mapping[_DictKey2, _DictValue2],
366 filter: Optional[Callable[[Hashable, Any], bool]]
367) -> Dict[Union[_DictKey1, _DictKey2], Union[_DictValue1, _DictValue2]]:
368# ) -> Generator[Tuple[Union[_DictKey1, _DictKey2], Union[_DictValue1, _DictValue2]], None, None]:
369 ... # pragma: no cover
372@overload
373def mergedicts(
374 m1: Mapping[_DictKey1, _DictValue1],
375 m2: Mapping[_DictKey2, _DictValue2],
376 m3: Mapping[_DictKey3, _DictValue3],
377 filter: Optional[Callable[[Hashable, Any], bool]]
378) -> Dict[Union[_DictKey1, _DictKey2, _DictKey3], Union[_DictValue1, _DictValue2, _DictValue3]]:
379#) -> Generator[Tuple[Union[_DictKey1, _DictKey2, _DictKey3], Union[_DictValue1, _DictValue2, _DictValue3]], None, None]:
380 ... # pragma: no cover
383@export
384def mergedicts(*dicts: Tuple[Dict, ...], filter: Nullable[Callable[[Hashable, Any], bool]] = None) -> Dict:
385 """
386 Merge multiple dictionaries into a single new dictionary.
388 If parameter ``filter`` isn't ``None``, then this function is applied to every element during the merge operation. If
389 it returns true, the dictionary element will be present in the resulting dictionary.
391 :param dicts: Tuple of dictionaries to merge as positional parameters.
392 :param filter: Optional filter function to apply to each dictionary element when merging.
393 :returns: A new dictionary containing the merge result.
394 :raises ValueError: If 'mergedicts' got called without any dictionaries parameters.
396 .. seealso::
398 `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>`__
399 """
400 if len(dicts) == 0:
401 raise ValueError(f"Called 'mergedicts' without any dictionary parameter.")
403 if filter is None:
404 return {k: v for d in dicts for k, v in d.items()}
405 else:
406 return {k: v for d in dicts for k, v in d.items() if filter(k, v)}
409@overload
410def zipdicts(
411 m1: Mapping[_DictKey, _DictValue1]
412) -> Generator[Tuple[_DictKey, _DictValue1], None, None]:
413 ... # pragma: no cover
416@overload
417def zipdicts(
418 m1: Mapping[_DictKey, _DictValue1],
419 m2: Mapping[_DictKey, _DictValue2]
420) -> Generator[Tuple[_DictKey, _DictValue1, _DictValue2], None, None]:
421 ... # pragma: no cover
424@overload
425def zipdicts(
426 m1: Mapping[_DictKey, _DictValue1],
427 m2: Mapping[_DictKey, _DictValue2],
428 m3: Mapping[_DictKey, _DictValue3]
429) -> Generator[Tuple[_DictKey, _DictValue1, _DictValue2, _DictValue3], None, None]:
430 ... # pragma: no cover
433@export
434def zipdicts(*dicts: Tuple[Dict, ...]) -> Generator[Tuple, None, None]:
435 """
436 Iterate multiple dictionaries simultaneously.
438 :param dicts: Tuple of dictionaries to iterate as positional parameters.
439 :returns: A generator returning a tuple containing the key and values of each dictionary in the order of
440 given dictionaries.
441 :raises ValueError: If 'zipdicts' got called without any dictionary parameters.
442 :raises ValueError: If not all dictionaries have the same length.
444 .. seealso::
446 The code is based on code snippets and ideas from:
448 * `zipping together Python dicts <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/101_zip_dict>`__ (MIT Lizense)
449 """
450 if len(dicts) == 0:
451 raise ValueError(f"Called 'zipdicts' without any dictionary parameter.")
453 if any(len(d) != len(dicts[0]) for d in dicts):
454 raise ValueError(f"All given dictionaries must have the same length.")
456 def gen(ds: Tuple[Dict, ...]) -> Generator[Tuple, None, None]:
457 for key, item0 in ds[0].items():
458 # WORKAROUND: using redundant parenthesis for Python 3.7 and pypy-3.10
459 yield key, item0, *(d[key] for d in ds[1:])
461 return gen(dicts)