pyTooling.Common

pyTooling/Common/__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# ==================================================================================================================== #
#             _____           _ _               ____                                                                   #
#  _ __  _   |_   _|__   ___ | (_)_ __   __ _  / ___|___  _ __ ___  _ __ ___   ___  _ __                               #
# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || |   / _ \| '_ ` _ \| '_ ` _ \ / _ \| '_ \                              #
# | |_) | |_| || | (_) | (_) | | | | | | (_| || |__| (_) | | | | | | | | | | | (_) | | | |                             #
# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____\___/|_| |_| |_|_| |_| |_|\___/|_| |_|                             #
# |_|    |___/                          |___/                                                                          #
# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#                                                                                                                      #
# License:                                                                                                             #
# ==================================================================================================================== #
# Copyright 2017-2024 Patrick Lehmann - Bötzingen, Germany                                                             #
#                                                                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
# you may not use this file except in compliance with the License.                                                     #
# You may obtain a copy of the License at                                                                              #
#                                                                                                                      #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
#                                                                                                                      #
# Unless required by applicable law or agreed to in writing, software                                                  #
# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
# See the License for the specific language governing permissions and                                                  #
# limitations under the License.                                                                                       #
#                                                                                                                      #
# SPDX-License-Identifier: Apache-2.0                                                                                  #
# ==================================================================================================================== #
#
"""
Common types, helper functions and classes.

.. hint:: See :ref:`high-level help <COMMON>` for explanations and usage examples.
"""
__author__ =        "Patrick Lehmann"
__email__ =         "Paebbels@gmail.com"
__copyright__ =     "2017-2024, Patrick Lehmann"
__license__ =       "Apache License, Version 2.0"
__version__ =       "6.1.0"
__keywords__ =      ["abstract", "argparse", "attributes", "bfs", "cli", "console", "data structure", "decorators",
					  "dfs", "exceptions", "generators", "generic library", "generic path", "graph", "installation",
					  "iterators", "licensing", "message logging", "meta-classes", "overloading", "override", "packaging",
					  "path", "platform", "setuptools", "shell", "singleton", "slots","terminal", "text user interface",
					  "timer", "tree", "TUI", "url", "versioning", "wheel"]
__issue_tracker__ = "https://GitHub.com/pyTooling/pyTooling/issues"

from collections import deque
from numbers     import Number
from typing      import Type, TypeVar, Callable, Generator, overload, Hashable, Optional, List
from typing      import Any, Dict, Tuple, Union, Mapping, Set, Iterable, Optional as Nullable

try:
	from pyTooling.Decorators import export
	from pyTooling.Platform   import Platform
except ModuleNotFoundError:  # pragma: no cover
	print("[pyTooling.Common] Could not import from 'pyTooling.*'!")

	try:
		from Decorators         import export
		from Platform           import Platform
	except ModuleNotFoundError as ex:  # pragma: no cover
		print("[pyTooling.Common] Could not import directly!")
		raise ex


__all__ = ["CurrentPlatform"]

CurrentPlatform = Platform()     #: Gathered information for the current platform.


@export
def isnestedclass(cls: Type, scope: Type) -> bool:
	"""
	Returns true, if the given class ``cls`` is a member on an outer class ``scope``.

	:param cls:   Class to check, if it's a nested class.
	:param scope: Outer class which is the outer scope of ``cls``.
	:returns:     ``True``, if ``cls`` is a nested class within ``scope``.
	"""
	for mroClass in scope.mro():
		for memberName in mroClass.__dict__:
			member = getattr(mroClass, memberName)
			if isinstance(member, Type):
				if cls is member:
					return True

	return False


@export
def getsizeof(obj: Any) -> int:
	"""
	Recursively calculate the "true" size of an object including complex members like ``__dict__``.

	:param obj: Object to calculate the size of.
	:returns:   True size of an object in bytes.

	.. admonition:: Background Information

	   The function :func:`sys.getsizeof` only returns the raw size of a Python object and doesn't account for the
	   overhead of e.g. ``_dict__`` to store dynamically allocated object members.

	.. seealso::

	   The code is based on code snippets and ideas from:

	   * `Compute Memory Footprint of an Object and its Contents <https://code.activestate.com/recipes/577504/>`__ (MIT Lizense)
	   * `How do I determine the size of an object in Python? <https://stackoverflow.com/a/30316760/3719459>`__ (CC BY-SA 4.0)
	   * `Python __slots__, slots, and object layout <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/080_python_slots>`__ (MIT Lizense)
	"""
	from sys import getsizeof as sys_getsizeof

	visitedIDs = set()  #: A set to track visited objects, so memory consumption isn't counted multiple times.

	def recurse(obj: Any) -> int:
		"""
		Nested function for recursion.

		:param obj: Subobject to calculate the size of.
		:returns:   Size of a subobject in bytes.
		"""
		# If already visited, return 0 bytes, so no additional bytes are accumulated
		objectID = id(obj)
		if objectID in visitedIDs:
			return 0
		else:
			visitedIDs.add(objectID)

		# Get objects raw size
		size: int = sys_getsizeof(obj)

		# Skip elementary types
		if isinstance(obj, (str, bytes, bytearray, range, Number)):
			pass
		# Handle iterables
		elif isinstance(obj, (tuple, list, Set, deque)):      # TODO: What about builtin "set", "frozenset" and "dict"?
			for item in obj:
				size += recurse(item)
		# Handle mappings
		elif isinstance(obj, Mapping) or hasattr(obj, 'items'):
			items = getattr(obj, 'items')
			# Check if obj.items is a bound method.
			if hasattr(items, "__self__"):
				itemView = items()
			else:
				itemView = {}  # bind(obj, items)
			for key, value in itemView:
				size += recurse(key) + recurse(value)

		# Accumulate members from __dict__
		if hasattr(obj, '__dict__'):
			v = vars(obj)
			size += recurse(v)

		# Accumulate members from __slots__
		if hasattr(obj, '__slots__') and obj.__slots__ is not None:
			for slot in obj.__slots__:
				if hasattr(obj, slot):
					size += recurse(getattr(obj, slot))

		return size

	return recurse(obj)


def bind(instance, func, methodName: Nullable[str] = None):
	"""
	Bind the function *func* to *instance*, with either provided name *as_name*
	or the existing name of *func*. The provided *func* should accept the
	instance as the first argument, i.e. "self".

	:param instance:
	:param func:
	:param methodName:
	:return:
	"""
	if methodName is None:
		methodName = func.__name__

	boundMethod = func.__get__(instance, instance.__class__)
	setattr(instance, methodName, boundMethod)

	return boundMethod


_Element = TypeVar("Element")


@export
def firstElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
	"""
	Returns the first element from an indexable.

	:param indexable: Indexable to get the first element from.
	:return:          First element.
	"""
	return indexable[0]


@export
def lastElement(indexable: Union[List[_Element], Tuple[_Element, ...]]) -> _Element:
	"""
	Returns the last element from an indexable.

	:param indexable: Indexable to get the last element from.
	:return:          Last element.
	"""
	return indexable[-1]


@export
def firstItem(iterable: Iterable[_Element]) -> _Element:
	"""
	Returns the first item from an iterable.

	:param iterable: Iterable to get the first item from.
	:return:         First item.
	"""
	i = iter(iterable)
	try:
		return next(i)
	except StopIteration:
		raise ValueError(f"Iterable contains no items.")


@export
def lastItem(iterable: Iterable[_Element]) -> _Element:
	"""
	Returns the last item from an iterable.

	:param iterable: Iterable to get the last item from.
	:return:         Last item.
	"""
	i = iter(iterable)
	try:
		element = next(i)
	except StopIteration:
		raise ValueError(f"Iterable contains no items.")

	for element in i:
		pass
	return element


_DictKey = TypeVar("_DictKey")
_DictKey1 = TypeVar("_DictKey1")
_DictKey2 = TypeVar("_DictKey2")
_DictKey3 = TypeVar("_DictKey3")
_DictValue1 = TypeVar("_DictValue1")
_DictValue2 = TypeVar("_DictValue2")
_DictValue3 = TypeVar("_DictValue3")


@export
def firstKey(d: Dict[_DictKey1, _DictValue1]) -> _DictKey1:
	"""
	Retrieves the first key from a dictionary's keys.

	:param d: Dictionary to get the first key from.
	:returns: The first key.
	"""
	if len(d) == 0:
		raise ValueError(f"Dictionary is empty.")

	return next(iter(d.keys()))


@export
def firstValue(d: Dict[_DictKey1, _DictValue1]) -> _DictValue1:
	"""
	Retrieves the first value from a dictionary's values.

	:param d: Dictionary to get the first value from.
	:returns: The first value.
	"""
	if len(d) == 0:
		raise ValueError(f"Dictionary is empty.")

	return next(iter(d.values()))


@export
def firstPair(d: Dict[_DictKey1, _DictValue1]) -> Tuple[_DictKey1, _DictValue1]:
	"""
	Retrieves the first key-value-pair from a dictionary.

	:param d: Dictionary to get the first key-value-pair from.
	:returns: The first key-value-pair as tuple.
	"""
	if len(d) == 0:
		raise ValueError(f"Dictionary is empty.")

	return next(iter(d.items()))


@overload
def mergedicts(
	m1: Mapping[_DictKey1, _DictValue1],
	filter: Optional[Callable[[Hashable, Any], bool]]
) -> Dict[Union[_DictKey1], Union[_DictValue1]]:
#) -> Generator[Tuple[Union[_DictKey1], Union[_DictValue1]], None, None]:
	...  # pragma: no cover


@overload
def mergedicts(
	m1: Mapping[_DictKey1, _DictValue1],
	m2: Mapping[_DictKey2, _DictValue2],
	filter: Optional[Callable[[Hashable, Any], bool]]
) -> Dict[Union[_DictKey1, _DictKey2], Union[_DictValue1, _DictValue2]]:
# ) -> Generator[Tuple[Union[_DictKey1, _DictKey2], Union[_DictValue1, _DictValue2]], None, None]:
	...  # pragma: no cover


@overload
def mergedicts(
	m1: Mapping[_DictKey1, _DictValue1],
	m2: Mapping[_DictKey2, _DictValue2],
	m3: Mapping[_DictKey3, _DictValue3],
	filter: Optional[Callable[[Hashable, Any], bool]]
) -> Dict[Union[_DictKey1, _DictKey2, _DictKey3], Union[_DictValue1, _DictValue2, _DictValue3]]:
#) -> Generator[Tuple[Union[_DictKey1, _DictKey2, _DictKey3], Union[_DictValue1, _DictValue2, _DictValue3]], None, None]:
	...  # pragma: no cover


@export
def mergedicts(*dicts: Tuple[Dict, ...], filter: Nullable[Callable[[Hashable, Any], bool]] = None) -> Dict:
	"""
	Merge multiple dictionaries into a single new dictionary.

	If parameter ``filter`` isn't ``None``, then this function is applied to every element during the merge operation. If
	it returns true, the dictionary element will be present in the resulting dictionary.

	:param dicts:  Tuple of dictionaries to merge as positional parameters.
	:param filter: Optional filter function to apply to each dictionary element when merging.
	:returns:      A new dictionary containing the merge result.

	.. seealso::

	   `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>`__
	"""
	if len(dicts) == 0:
		raise ValueError(f"Called 'mergedicts' without any dictionary parameter.")

	if filter is None:
		return {k: v for d in dicts for k, v in d.items()}
	else:
		return {k: v for d in dicts for k, v in d.items() if filter(k, v)}


@overload
def zipdicts(
	m1: Mapping[_DictKey, _DictValue1]
) -> Generator[Tuple[_DictKey, _DictValue1], None, None]:
	...  # pragma: no cover


@overload
def zipdicts(
	m1: Mapping[_DictKey, _DictValue1],
	m2: Mapping[_DictKey, _DictValue2]
) -> Generator[Tuple[_DictKey, _DictValue1, _DictValue2], None, None]:
	...  # pragma: no cover


@overload
def zipdicts(
	m1: Mapping[_DictKey, _DictValue1],
	m2: Mapping[_DictKey, _DictValue2],
	m3: Mapping[_DictKey, _DictValue3]
) -> Generator[Tuple[_DictKey, _DictValue1, _DictValue2, _DictValue3], None, None]:
	...  # pragma: no cover


@export
def zipdicts(*dicts: Tuple[Dict, ...]) -> Generator[Tuple, None, None]:
	"""
	Iterate multiple dictionaries simultaneously.

	:param dicts: Tuple of dictionaries to iterate as positional parameters.
	:returns:     A generator returning a tuple containing the key and values of each dictionary in the order of given
	              dictionaries.

	.. seealso::

	   The code is based on code snippets and ideas from:

	   * `zipping together Python dicts <https://github.com/mCodingLLC/VideosSampleCode/tree/master/videos/101_zip_dict>`__ (MIT Lizense)
	"""
	if len(dicts) == 0:
		raise ValueError(f"Called 'zipdicts' without any dictionary parameter.")

	if any(len(d) != len(dicts[0]) for d in dicts):
		raise ValueError(f"All given dictionaries must have the same length.")

	def gen(ds: Tuple[Dict, ...]) -> Generator[Tuple, None, None]:
		for key, item0 in ds[0].items():
			# WORKAROUND: using redundant parenthesis for Python 3.7 and pypy-3.10
			yield (key, item0, *(d[key] for d in ds[1:]))

	return gen(dicts)