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 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
|
# ==================================================================================================================== #
# _____ _ _ __ __ _ ____ _ #
# _ __ _ |_ _|__ ___ | (_)_ __ __ _ | \/ | ___| |_ __ _ / ___| | __ _ ___ ___ ___ ___ #
# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` | | |\/| |/ _ \ __/ _` | | | |/ _` / __/ __|/ _ \/ __| #
# | |_) | |_| || | (_) | (_) | | | | | | (_| |_| | | | __/ || (_| | |___| | (_| \__ \__ \ __/\__ \ #
# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)_| |_|\___|\__\__,_|\____|_|\__,_|___/___/\___||___/ #
# |_| |___/ |___/ #
# ==================================================================================================================== #
# Authors: #
# Patrick Lehmann #
# Sven Köhler #
# #
# License: #
# ==================================================================================================================== #
# Copyright 2017-2026 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 #
# ==================================================================================================================== #
#
"""
The MetaClasses package implements Python meta-classes (classes to construct other classes in Python).
.. hint::
See :ref:`high-level help <META>` for explanations and usage examples.
"""
from functools import wraps
from itertools import chain
from sys import version_info
from threading import Condition
from types import FunctionType, MethodType
from typing import Any, Tuple, List, Dict, Callable, Generator, Set, Iterator, Iterable, Union, NoReturn, Self
from typing import Type, TypeVar, Generic, _GenericAlias, ClassVar, Optional as Nullable
try:
from pyTooling.Exceptions import ToolingException
from pyTooling.Decorators import export, readonly
except (ImportError, ModuleNotFoundError): # pragma: no cover
print("[pyTooling.MetaClasses] Could not import from 'pyTooling.*'!")
try:
from Exceptions import ToolingException
from Decorators import export, readonly
except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
print("[pyTooling.MetaClasses] Could not import directly!")
raise ex
__all__ = ["M"]
TAttr = TypeVar("TAttr") # , bound='Attribute')
"""A type variable for :class:`~pyTooling.Attributes.Attribute`."""
TAttributeFilter = Union[TAttr, Iterable[TAttr], None]
"""A type hint for a predicate parameter that accepts either a single :class:`~pyTooling.Attributes.Attribute` or an
iterable of those."""
@export
class ExtendedTypeError(ToolingException):
"""The exception is raised by the meta-class :class:`~pyTooling.Metaclasses.ExtendedType`."""
@export
class BaseClassWithoutSlotsError(ExtendedTypeError):
"""
This exception is raised when a class using ``__slots__`` inherits from at-least one base-class not using ``__slots__``.
.. seealso::
* :ref:`Python data model for slots <slots>`
* :term:`Glossary entry __slots__ <__slots__>`
"""
@export
class BaseClassWithNonEmptySlotsError(ExtendedTypeError):
"""
This exception is raised when a mixin-class uses slots, but Python prohibits slots.
.. important::
To fulfill Python's requirements on slots, pyTooling uses slots only on the prinmary inheritance line.
Mixin-classes collect slots, which get materialized when the mixin-class (secondary inheritance lines) gets merged
into the primary inheritance line.
"""
@export
class BaseClassIsNotAMixinError(ExtendedTypeError):
pass
@export
class DuplicateFieldInSlotsError(ExtendedTypeError):
"""
This exception is raised when a slot name is used multiple times within the inheritance hierarchy.
"""
@export
class AbstractClassError(ExtendedTypeError):
"""
This exception is raised, when a class contains methods marked with *abstractmethod* or *must-override*.
.. seealso::
:func:`@abstractmethod <pyTooling.MetaClasses.abstractmethod>`
|rarr| Mark a method as *abstract*.
:func:`@mustoverride <pyTooling.MetaClasses.mustoverride>`
|rarr| Mark a method as *must overrride*.
:exc:`~MustOverrideClassError`
|rarr| Exception raised, if a method is marked as *must-override*.
"""
@export
class MustOverrideClassError(AbstractClassError):
"""
This exception is raised, when a class contains methods marked with *must-override*.
.. seealso::
:func:`@abstractmethod <pyTooling.MetaClasses.abstractmethod>`
|rarr| Mark a method as *abstract*.
:func:`@mustoverride <pyTooling.MetaClasses.mustoverride>`
|rarr| Mark a method as *must overrride*.
:exc:`~AbstractClassError`
|rarr| Exception raised, if a method is marked as *abstract*.
"""
# """
# Metaclass that allows multiple dispatch of methods based on method signatures.
#
# .. seealso:
#
# `Python Cookbook - Multiple dispatch with function annotations <https://GitHub.com/dabeaz/python-cookbook/blob/master/src/9/multiple_dispatch_with_function_annotations/example1.py?ts=2>`__
# """
M = TypeVar("M", bound=Callable) #: A type variable for methods.
@export
def slotted(cls):
if cls.__class__ is type:
metacls = ExtendedType
elif issubclass(cls.__class__, ExtendedType):
metacls = cls.__class__
for method in cls.__methods__:
delattr(method, "__classobj__")
else:
raise ExtendedTypeError("Class uses an incompatible meta-class.") # FIXME: create exception for it?
bases = tuple(base for base in cls.__bases__ if base is not object)
slots = cls.__dict__["__slots__"] if "__slots__" in cls.__dict__ else tuple()
members = {
"__qualname__": cls.__qualname__
}
for key, value in cls.__dict__.items():
if key not in slots:
members[key] = value
return metacls(cls.__name__, bases, members, slots=True)
@export
def mixin(cls):
if cls.__class__ is type:
metacls = ExtendedType
elif issubclass(cls.__class__, ExtendedType):
metacls = cls.__class__
for method in cls.__methods__:
delattr(method, "__classobj__")
else:
raise ExtendedTypeError("Class uses an incompatible meta-class.") # FIXME: create exception for it?
bases = tuple(base for base in cls.__bases__ if base is not object)
slots = cls.__dict__["__slots__"] if "__slots__" in cls.__dict__ else tuple()
members = {
"__qualname__": cls.__qualname__
}
for key, value in cls.__dict__.items():
if key not in slots:
members[key] = value
return metacls(cls.__name__, bases, members, mixin=True)
@export
def singleton(cls):
if cls.__class__ is type:
metacls = ExtendedType
elif issubclass(cls.__class__, ExtendedType):
metacls = cls.__class__
for method in cls.__methods__:
delattr(method, "__classobj__")
else:
raise ExtendedTypeError("Class uses an incompatible meta-class.") # FIXME: create exception for it?
bases = tuple(base for base in cls.__bases__ if base is not object)
slots = cls.__dict__["__slots__"] if "__slots__" in cls.__dict__ else tuple()
members = {
"__qualname__": cls.__qualname__
}
for key, value in cls.__dict__.items():
if key not in slots:
members[key] = value
return metacls(cls.__name__, bases, members, singleton=True)
@export
def abstractmethod(method: M) -> M:
"""
Mark a method as *abstract* and replace the implementation with a new method raising a :exc:`NotImplementedError`.
The original method is stored in ``<method>.__wrapped__`` and it's doc-string is copied to the replacing method. In
additional field ``<method>.__abstract__`` is added.
.. warning::
This decorator should be used in combination with meta-class :class:`~pyTooling.Metaclasses.ExtendedType`.
Otherwise, an abstract class itself doesn't throw a :exc:`~pyTooling.Exceptions.AbstractClassError` at
instantiation.
.. admonition:: ``example.py``
.. code-block:: python
class Data(mataclass=ExtendedType):
@abstractmethod
def method(self) -> bool:
'''This method needs to be implemented'''
:param method: Method that is marked as *abstract*.
:returns: Replacement method, which raises a :exc:`NotImplementedError`.
.. seealso::
* :exc:`~pyTooling.Exceptions.AbstractClassError`
* :func:`~pyTooling.Metaclasses.mustoverride`
* :func:`~pyTooling.Metaclasses.notimplemented`
"""
@wraps(method)
def func(self) -> NoReturn:
raise NotImplementedError(f"Method '{method.__name__}' is abstract and needs to be overridden in a derived class.")
func.__abstract__ = True
return func
@export
def mustoverride(method: M) -> M:
"""
Mark a method as *must-override*.
The returned function is the original function, but with an additional field ``<method>.____mustOverride__``, so a
meta-class can identify a *must-override* method and raise an error. Such an error is not raised if the method is
overridden by an inheriting class.
A *must-override* methods can offer a partial implementation, which is called via ``super()...``.
.. warning::
This decorator needs to be used in combination with meta-class :class:`~pyTooling.Metaclasses.ExtendedType`.
Otherwise, an abstract class itself doesn't throw a :exc:`~pyTooling.Exceptions.MustOverrideClassError` at
instantiation.
.. admonition:: ``example.py``
.. code-block:: python
class Data(mataclass=ExtendedType):
@mustoverride
def method(self):
'''This is a very basic implementation'''
:param method: Method that is marked as *must-override*.
:returns: Same method, but with additional ``<method>.__mustOverride__`` field.
.. seealso::
* :exc:`~pyTooling.Exceptions.MustOverrideClassError`
* :func:`~pyTooling.Metaclasses.abstractmethod`
* :func:`~pyTooling.Metaclasses.notimplemented`
"""
method.__mustOverride__ = True
return method
# @export
# def overloadable(method: M) -> M:
# method.__overloadable__ = True
# return method
# @export
# class DispatchableMethod:
# """Represents a single multimethod."""
#
# _methods: Dict[Tuple, Callable]
# __name__: str
# __slots__ = ("_methods", "__name__")
#
# def __init__(self, name: str) -> None:
# self.__name__ = name
# self._methods = {}
#
# def __call__(self, *args: Any):
# """Call a method based on type signature of the arguments."""
# types = tuple(type(arg) for arg in args[1:])
# meth = self._methods.get(types, None)
# if meth:
# return meth(*args)
# else:
# raise TypeError(f"No matching method for types {types}.")
#
# def __get__(self, instance, cls): # Starting with Python 3.11+, use typing.Self as return type
# """Descriptor method needed to make calls work in a class."""
# if instance is not None:
# return MethodType(self, instance)
# else:
# return self
#
# def register(self, method: Callable) -> None:
# """Register a new method as a dispatchable."""
#
# # Build a signature from the method's type annotations
# sig = signature(method)
# types: List[Type] = []
#
# for name, parameter in sig.parameters.items():
# if name == "self":
# continue
#
# if parameter.annotation is Parameter.empty:
# raise TypeError(f"Parameter '{name}' in method '{method.__name__}' must be annotated with a type.")
#
# if not isinstance(parameter.annotation, type):
# raise TypeError(f"Parameter '{name}' in method '{method.__name__}' annotation must be a type.")
#
# if parameter.default is not Parameter.empty:
# self._methods[tuple(types)] = method
#
# types.append(parameter.annotation)
#
# self._methods[tuple(types)] = method
# @export
# class DispatchDictionary(dict):
# """Special dictionary to build dispatchable methods in a metaclass."""
#
# def __setitem__(self, key: str, value: Any):
# if callable(value) and key in self:
# # If key already exists, it must be a dispatchable method or callable
# currentValue = self[key]
# if isinstance(currentValue, DispatchableMethod):
# currentValue.register(value)
# else:
# dispatchable = DispatchableMethod(key)
# dispatchable.register(currentValue)
# dispatchable.register(value)
#
# super().__setitem__(key, dispatchable)
# else:
# super().__setitem__(key, value)
@export
class ExtendedType(type):
"""
An updates meta-class to construct new classes with an extended feature set.
.. todo:: META::ExtendedType Needs documentation.
.. todo:: META::ExtendedType allow __dict__ and __weakref__ if slotted is enabled
.. rubric:: Features:
* Store object members more efficiently in ``__slots__`` instead of ``_dict__``.
* Implement ``__slots__`` only on primary inheritance line.
* Collect class variables on secondary inheritance lines (mixin-classes) and defer implementation as ``__slots__``.
* Handle object state exporting and importing for slots (:mod:`pickle` support) via ``__getstate__``/``__setstate__``.
* Allow only a single instance to be created (:term:`singleton`). |br|
Further instantiations will return the previously create instance (identical object).
* Define methods as :term:`abstract <abstract method>` or :term:`must-override <mustoverride method>` and prohibit
instantiation of :term:`abstract classes <abstract class>`.
.. #* Allow method overloading and dispatch overloads based on argument signatures.
.. rubric:: Added class fields:
:__slotted__: True, if class uses `__slots__`.
:__allSlots__: Set of class fields stored in slots for all classes in the inheritance hierarchy.
:__slots__: Tuple of class fields stored in slots for current class in the inheritance hierarchy. |br|
See :pep:`253` for details.
:__isMixin__: True, if class is a mixin-class
:__mixinSlots__: List of collected slots from secondary inheritance hierarchy (mixin hierarchy).
:__methods__: List of methods.
:__methodsWithAttributes__: List of methods with pyTooling attributes.
:__abstractMethods__: List of abstract methods, which need to be implemented in the next class hierarchy levels.
:__isAbstract__: True, if class is abstract.
:__isSingleton__: True, if class is a singleton
:__singletonInstanceCond__: Condition variable to protect the singleton creation.
:__singletonInstanceInit__: Singleton is initialized.
:__singletonInstanceCache__: The singleton object, once created.
:__pyattr__: List of class attributes.
.. rubric:: Added class properties:
:HasClassAttributes: Read-only property to check if the class has Attributes.
:HasMethodAttributes: Read-only property to check if the class has methods with Attributes.
.. rubric:: Added methods:
If slots are used, the following methods are added to support :mod:`pickle`:
:__getstate__: Export an object's state for serialization. |br|
See :pep:`307` for details.
:__setstate__: Import an object's state for deserialization. |br|
See :pep:`307` for details.
.. rubric:: Modified ``__new__`` method:
If class is a singleton, ``__new__`` will be replaced by a wrapper method. This wrapper is marked with ``__singleton_wrapper__``.
If class is abstract, ``__new__`` will be replaced by a method raising an exception. This replacement is marked with ``__raises_abstract_class_error__``.
.. rubric:: Modified ``__init__`` method:
If class is a singleton, ``__init__`` will be replaced by a wrapper method. This wrapper is marked by ``__singleton_wrapper__``.
.. rubric:: Modified abstract methods:
If a method is abstract, its marked with ``__abstract__``. |br|
If a method is must override, its marked with ``__mustOverride__``.
"""
# @classmethod
# def __prepare__(cls, className, baseClasses, slots: bool = False, mixin: bool = False, singleton: bool = False):
# return DispatchDictionary()
def __new__(
self,
className: str,
baseClasses: Tuple[type],
members: Dict[str, Any],
slots: bool = False,
mixin: bool = False,
singleton: bool = False
) -> Self:
"""
Construct a new class using this :term:`meta-class`.
:param className: The name of the class to construct.
:param baseClasses: The tuple of :term:`base-classes <base-class>` the class is derived from.
:param members: The dictionary of members for the constructed class.
:param slots: If true, store object attributes in :term:`__slots__ <slots>` instead of ``__dict__``.
:param mixin: If true, make the class a :term:`Mixin-Class`.
If false, create slots if ``slots`` is true.
If none, preserve behavior of primary base-class.
:param singleton: If true, make the class a :term:`Singleton`.
:returns: The new class.
:raises AttributeError: If base-class has no '__slots__' attribute.
:raises AttributeError: If slot already exists in base-class.
"""
try:
from pyTooling.Attributes import ATTRIBUTES_MEMBER_NAME, AttributeScope
except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
from Attributes import ATTRIBUTES_MEMBER_NAME, AttributeScope
# Inherit 'slots' feature from primary base-class
if len(baseClasses) > 0:
primaryBaseClass = baseClasses[0]
if isinstance(primaryBaseClass, self):
slots = primaryBaseClass.__slotted__
# Compute slots and mixin-slots from annotated fields as well as class- and object-fields with initial values.
classFields, objectFields = self._computeSlots(className, baseClasses, members, slots, mixin)
# Compute abstract methods
abstractMethods, members = self._checkForAbstractMethods(baseClasses, members)
# Create a new class
newClass = type.__new__(self, className, baseClasses, members)
# Apply class fields
for fieldName, typeAnnotation in classFields.items():
setattr(newClass, fieldName, typeAnnotation)
# Search in inheritance tree for abstract methods
newClass.__abstractMethods__ = abstractMethods
newClass.__isAbstract__ = self._wrapNewMethodIfAbstract(newClass)
newClass.__isSingleton__ = self._wrapNewMethodIfSingleton(newClass, singleton)
if slots:
# If slots are used, implement __getstate__/__setstate__ API to support serialization using pickle.
if "__getstate__" not in members:
def __getstate__(self) -> Dict[str, Any]:
try:
return {slotName: getattr(self, slotName) for slotName in self.__allSlots__}
except AttributeError as ex:
raise ExtendedTypeError(f"Unassigned field '{ex.name}' in object '{self}' of type '{self.__class__.__name__}'.") from ex
newClass.__getstate__ = __getstate__
if "__setstate__" not in members:
def __setstate__(self, state: Dict[str, Any]) -> None:
if self.__allSlots__ != (slots := set(state.keys())):
if len(diff := self.__allSlots__.difference(slots)) > 0:
raise ExtendedTypeError(f"""Missing fields in parameter 'state': '{"', '".join(diff)}'""") # WORKAROUND: Python <3.12
else:
diff = slots.difference(self.__allSlots__)
raise ExtendedTypeError(f"""Unexpected fields in parameter 'state': '{"', '".join(diff)}'""") # WORKAROUND: Python <3.12
for slotName, value in state.items():
setattr(self, slotName, value)
newClass.__setstate__ = __setstate__
# Check for inherited class attributes
attributes = []
setattr(newClass, ATTRIBUTES_MEMBER_NAME, attributes)
for base in baseClasses:
if hasattr(base, ATTRIBUTES_MEMBER_NAME):
pyAttr = getattr(base, ATTRIBUTES_MEMBER_NAME)
for att in pyAttr:
if AttributeScope.Class in att.Scope:
attributes.append(att)
att.__class__._classes.append(newClass)
# Check methods for attributes
methods, methodsWithAttributes = self._findMethods(newClass, baseClasses, members)
# Add new fields for found methods
newClass.__methods__ = tuple(methods)
newClass.__methodsWithAttributes__ = tuple(methodsWithAttributes)
# Additional methods on a class
def GetMethodsWithAttributes(self, predicate: Nullable[TAttributeFilter[TAttr]] = None) -> Dict[Callable, Tuple["Attribute", ...]]:
"""
:param predicate:
:return:
:raises ValueError:
:raises ValueError:
"""
try:
from ..Attributes import Attribute
except (ImportError, ModuleNotFoundError): # pragma: no cover
try:
from Attributes import Attribute
except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
raise ex
if predicate is None:
predicate = Attribute
elif isinstance(predicate, Iterable):
for attribute in predicate:
if not issubclass(attribute, Attribute):
raise ValueError(f"Parameter 'predicate' contains an element which is not a sub-class of 'Attribute'.")
predicate = tuple(predicate)
elif not issubclass(predicate, Attribute):
raise ValueError(f"Parameter 'predicate' is not a sub-class of 'Attribute'.")
methodAttributePairs = {}
for method in newClass.__methodsWithAttributes__:
matchingAttributes = []
for attribute in method.__pyattr__:
if isinstance(attribute, predicate):
matchingAttributes.append(attribute)
if len(matchingAttributes) > 0:
methodAttributePairs[method] = tuple(matchingAttributes)
return methodAttributePairs
newClass.GetMethodsWithAttributes = classmethod(GetMethodsWithAttributes)
GetMethodsWithAttributes.__qualname__ = f"{className}.{GetMethodsWithAttributes.__name__}"
# GetMethods(predicate) -> dict[method, list[attribute]] / generator
# GetClassAtrributes -> list[attributes] / generator
# MethodHasAttributes(predicate) -> bool
# GetAttribute
return newClass
@classmethod
def _findMethods(
self,
newClass: "ExtendedType",
baseClasses: Tuple[type],
members: Dict[str, Any]
) -> Tuple[List[MethodType], List[MethodType]]:
"""
Find methods and methods with :mod:`pyTooling.Attributes`.
.. todo::
Describe algorithm.
:param newClass: Newly created class instance.
:param baseClasses: The tuple of :term:`base-classes <base-class>` the class is derived from.
:param members: Members of the new class.
:return:
"""
try:
from ..Attributes import Attribute
except (ImportError, ModuleNotFoundError): # pragma: no cover
try:
from Attributes import Attribute
except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
raise ex
# Embedded bind function due to circular dependencies.
def bind(instance: object, func: FunctionType, methodName: Nullable[str] = None):
if methodName is None:
methodName = func.__name__
boundMethod = func.__get__(instance, instance.__class__)
setattr(instance, methodName, boundMethod)
return boundMethod
methods = []
methodsWithAttributes = []
attributeIndex = {}
for base in baseClasses:
if hasattr(base, "__methodsWithAttributes__"):
methodsWithAttributes.extend(base.__methodsWithAttributes__)
for memberName, member in members.items():
if isinstance(member, FunctionType):
method = newClass.__dict__[memberName]
if hasattr(method, "__classobj__") and getattr(method, "__classobj__") is not newClass:
raise TypeError(f"Method '{memberName}' is used by multiple classes: {method.__classobj__} and {newClass}.")
else:
setattr(method, "__classobj__", newClass)
def GetAttributes(inst: Any, predicate: Nullable[Type[Attribute]] = None) -> Tuple[Attribute, ...]:
results = []
try:
for attribute in inst.__pyattr__: # type: Attribute
if isinstance(attribute, predicate):
results.append(attribute)
return tuple(results)
except AttributeError:
return tuple()
method.GetAttributes = bind(method, GetAttributes)
methods.append(method)
# print(f" convert function: '{memberName}' to method")
# print(f" {member}")
if "__pyattr__" in member.__dict__:
attributes = member.__pyattr__ # type: List[Attribute]
if isinstance(attributes, list) and len(attributes) > 0:
methodsWithAttributes.append(member)
for attribute in attributes:
attribute._functions.remove(method)
attribute._methods.append(method)
# print(f" attributes: {attribute.__class__.__name__}")
if attribute not in attributeIndex:
attributeIndex[attribute] = [member]
else:
attributeIndex[attribute].append(member)
# else:
# print(f" But has no attributes.")
# else:
# print(f" ?? {memberName}")
return methods, methodsWithAttributes
@classmethod
def _computeSlots(
self,
className: str,
baseClasses: Tuple[type],
members: Dict[str, Any],
slots: bool,
mixin: bool
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
Compute which field are listed in __slots__ and which need to be initialized in an instance or class.
.. todo::
Describe algorithm.
:param className: The name of the class to construct.
:param baseClasses: Tuple of base-classes.
:param members: Dictionary of class members.
:param slots: True, if the class should setup ``__slots__``.
:param mixin: True, if the class should behave as a mixin-class.
:returns: A 2-tuple with a dictionary of class members and object members.
"""
# Compute which field are listed in __slots__ and which need to be initialized in an instance or class.
slottedFields = []
classFields = {}
objectFields = {}
if slots or mixin:
# If slots are used, all base classes must use __slots__.
for baseClass in self._iterateBaseClasses(baseClasses):
# Exclude object as a special case
if baseClass is object or baseClass is Generic:
continue
if not hasattr(baseClass, "__slots__"):
ex = BaseClassWithoutSlotsError(f"Base-classes '{baseClass.__name__}' doesn't use '__slots__'.")
ex.add_note(f"All base-classes of a class using '__slots__' must use '__slots__' itself.")
raise ex
# FIXME: should have a check for non-empty slots on secondary base-classes too
# Copy all field names from primary base-class' __slots__, which are later needed for error checking.
inheritedSlottedFields = {}
if len(baseClasses) > 0:
for base in reversed(baseClasses[0].mro()):
# Exclude object as a special case
if base is object or base is Generic:
continue
for annotation in base.__slots__:
inheritedSlottedFields[annotation] = base
# When adding annotated fields to slottedFields, check if name was not used in inheritance hierarchy.
if "__annotations__" in members:
# WORKAROUND: LEGACY SUPPORT Python <= 3.13
# Accessing annotations was changed in Python 3.14.
# The necessary 'annotationlib' is not available for older Python versions.
annotations: Dict[str, Any] = members.get("__annotations__", {})
elif version_info >= (3, 14) and (annotate := members.get("__annotate_func__", None)) is not None:
from annotationlib import Format
annotations: Dict[str, Any] = annotate(Format.VALUE)
else:
annotations = {}
for fieldName, typeAnnotation in annotations.items():
if fieldName in inheritedSlottedFields:
cls = inheritedSlottedFields[fieldName]
raise AttributeError(f"Slot '{fieldName}' already exists in base-class '{cls.__module__}.{cls.__name__}'.")
# If annotated field is a ClassVar, and it has an initial value
# * copy field and initial value to classFields dictionary
# * remove field from members
if isinstance(typeAnnotation, _GenericAlias) and typeAnnotation.__origin__ is ClassVar and fieldName in members:
classFields[fieldName] = members[fieldName]
del members[fieldName]
# If an annotated field has an initial value
# * copy field and initial value to objectFields dictionary
# * remove field from members
elif fieldName in members:
slottedFields.append(fieldName)
objectFields[fieldName] = members[fieldName]
del members[fieldName]
else:
slottedFields.append(fieldName)
mixinSlots = self._aggregateMixinSlots(className, baseClasses)
else:
# When adding annotated fields to slottedFields, check if name was not used in inheritance hierarchy.
annotations: Dict[str, Any] = members.get("__annotations__", {})
for fieldName, typeAnnotation in annotations.items():
# If annotated field is a ClassVar, and it has an initial value
# * copy field and initial value to classFields dictionary
# * remove field from members
if isinstance(typeAnnotation, _GenericAlias) and typeAnnotation.__origin__ is ClassVar and fieldName in members:
classFields[fieldName] = members[fieldName]
del members[fieldName]
# FIXME: search for fields without annotation
if mixin:
mixinSlots.extend(slottedFields)
members["__slotted__"] = True
members["__slots__"] = tuple()
members["__allSlots__"] = set()
members["__isMixin__"] = True
members["__mixinSlots__"] = tuple(mixinSlots)
elif slots:
slottedFields.extend(mixinSlots)
members["__slotted__"] = True
members["__slots__"] = tuple(slottedFields)
members["__allSlots__"] = set(chain(slottedFields, inheritedSlottedFields.keys()))
members["__isMixin__"] = False
members["__mixinSlots__"] = tuple()
else:
members["__slotted__"] = False
# NO __slots__
# members["__allSlots__"] = set()
members["__isMixin__"] = False
members["__mixinSlots__"] = tuple()
return classFields, objectFields
@classmethod
def _aggregateMixinSlots(self, className: str, baseClasses: Tuple[type]) -> List[str]:
"""
Aggregate slot names requested by mixin-base-classes.
.. todo::
Describe algorithm.
:param className: The name of the class to construct.
:param baseClasses: The tuple of :term:`base-classes <base-class>` the class is derived from.
:returns: A list of slot names.
"""
mixinSlots = []
if len(baseClasses) > 0:
# If class has base-classes ensure only the primary inheritance path uses slots and all secondary inheritance
# paths have an empty slots tuple. Otherwise, raise a BaseClassWithNonEmptySlotsError.
inheritancePaths = [path for path in self._iterateBaseClassPaths(baseClasses)]
primaryInharitancePath: Set[type] = set(inheritancePaths[0])
for typePath in inheritancePaths[1:]:
for t in typePath:
if hasattr(t, "__slots__") and len(t.__slots__) != 0 and t not in primaryInharitancePath:
ex = BaseClassWithNonEmptySlotsError(f"Base-class '{t.__name__}' has non-empty __slots__ and can't be used as a direct or indirect base-class for '{className}'.")
ex.add_note(f"In Python, only one inheritance branch can use non-empty __slots__.")
# ex.add_note(f"With ExtendedType, only the primary base-class can use non-empty __slots__.")
# ex.add_note(f"Secondary base-classes should be marked as mixin-classes.")
raise ex
# If current class is set to be a mixin, then aggregate all mixinSlots in a list.
# Ensure all base-classes are either constructed
# * by meta-class ExtendedType, or
# * use no slots, or
# * are typing.Generic
# If it was constructed by ExtendedType, then ensure this class itself is a mixin-class.
for baseClass in baseClasses: # type: ExtendedType
if isinstance(baseClass, _GenericAlias) and baseClass.__origin__ is Generic:
pass
elif baseClass.__class__ is self and baseClass.__isMixin__:
mixinSlots.extend(baseClass.__mixinSlots__)
elif hasattr(baseClass, "__mixinSlots__"):
mixinSlots.extend(baseClass.__mixinSlots__)
return mixinSlots
@classmethod
def _iterateBaseClasses(metacls, baseClasses: Tuple[type]) -> Generator[type, None, None]:
"""
Return a generator to iterate (visit) all base-classes ...
.. todo::
Describe iteration order.
:param baseClasses: The tuple of :term:`base-classes <base-class>` the class is derived from.
:returns: Generator to iterate all base-classes.
"""
if len(baseClasses) == 0:
return
visited: Set[type] = set()
iteratorStack: List[Iterator[type]] = list()
for baseClass in baseClasses:
yield baseClass
visited.add(baseClass)
iteratorStack.append(iter(baseClass.__bases__))
while True:
try:
base = next(iteratorStack[-1]) # type: type
if base not in visited:
yield base
if len(base.__bases__) > 0:
iteratorStack.append(iter(base.__bases__))
else:
continue
except StopIteration:
iteratorStack.pop()
if len(iteratorStack) == 0:
break
@classmethod
def _iterateBaseClassPaths(metacls, baseClasses: Tuple[type]) -> Generator[Tuple[type, ...], None, None]:
"""
Return a generator to iterate all possible inheritance paths for a given list of base-classes.
An inheritance path is expressed as a tuple of base-classes from current base-class (left-most item) to
:class:`object` (right-most item).
:param baseClasses: The tuple of :term:`base-classes <base-class>` the class is derived from.
:returns: Generator to iterate all inheritance paths. |br|
An inheritance path is a tuple of types (base-classes).
"""
if len(baseClasses) == 0:
return
typeStack: List[type] = list()
iteratorStack: List[Iterator[type]] = list()
for baseClass in baseClasses:
typeStack.append(baseClass)
iteratorStack.append(iter(baseClass.__bases__))
while True:
try:
base = next(iteratorStack[-1]) # type: type
typeStack.append(base)
if len(base.__bases__) == 0:
yield tuple(typeStack)
typeStack.pop()
else:
iteratorStack.append(iter(base.__bases__))
except StopIteration:
typeStack.pop()
iteratorStack.pop()
if len(typeStack) == 0:
break
@classmethod
def _checkForAbstractMethods(metacls, baseClasses: Tuple[type], members: Dict[str, Any]) -> Tuple[Dict[str, Callable], Dict[str, Any]]:
"""
Check if the current class contains abstract methods and return a tuple of them.
These abstract methods might be inherited from any base-class. If there are inherited abstract methods, check if
they are now implemented (overridden) by the current class that's right now constructed.
:param baseClasses: The tuple of :term:`base-classes <base-class>` the class is derived from.
:param members: The dictionary of members for the constructed class.
:returns: A tuple of abstract method's names.
"""
abstractMethods = {}
if baseClasses:
# Aggregate all abstract methods from all base-classes.
for baseClass in baseClasses:
if hasattr(baseClass, "__abstractMethods__"):
abstractMethods.update(baseClass.__abstractMethods__)
for base in baseClasses:
for memberName, member in base.__dict__.items():
if (memberName in abstractMethods and isinstance(member, FunctionType) and
not (hasattr(member, "__abstract__") or hasattr(member, "__mustOverride__"))):
def outer(method):
@wraps(method)
def inner(cls, *args: Any, **kwargs: Any):
return method(cls, *args, **kwargs)
return inner
members[memberName] = outer(member)
# Check if methods are marked:
# * If so, add them to list of abstract methods
# * If not, method is now implemented and removed from list
for memberName, member in members.items():
if callable(member):
if ((hasattr(member, "__abstract__") and member.__abstract__) or
(hasattr(member, "__mustOverride__") and member.__mustOverride__)):
abstractMethods[memberName] = member
elif memberName in abstractMethods:
del abstractMethods[memberName]
return abstractMethods, members
@classmethod
def _wrapNewMethodIfSingleton(metacls, newClass, singleton: bool) -> bool:
"""
If a class is a singleton, wrap the ``_new__`` method, so it returns a cached object, if a first object was created.
Only the first object creation initializes the object.
This implementation is threadsafe.
:param newClass: The newly constructed class for further modifications.
:param singleton: If ``True``, the class allows only a single instance to exist.
:returns: ``True``, if the class is a singleton.
"""
if hasattr(newClass, "__isSingleton__"):
singleton = newClass.__isSingleton__
if singleton:
oldnew = newClass.__new__
if hasattr(oldnew, "__singleton_wrapper__"):
oldnew = oldnew.__wrapped__
oldinit = newClass.__init__
if hasattr(oldinit, "__singleton_wrapper__"):
oldinit = oldinit.__wrapped__
@wraps(oldnew)
def singleton_new(cls, *args: Any, **kwargs: Any):
with cls.__singletonInstanceCond__:
if cls.__singletonInstanceCache__ is None:
obj = oldnew(cls, *args, **kwargs)
cls.__singletonInstanceCache__ = obj
else:
obj = cls.__singletonInstanceCache__
return obj
@wraps(oldinit)
def singleton_init(self, *args: Any, **kwargs: Any):
cls = self.__class__
cv = cls.__singletonInstanceCond__
with cv:
if cls.__singletonInstanceInit__:
oldinit(self, *args, **kwargs)
cls.__singletonInstanceInit__ = False
cv.notify_all()
elif args or kwargs:
raise ValueError(f"A further instance of a singleton can't be reinitialized with parameters.")
else:
while cls.__singletonInstanceInit__:
cv.wait()
singleton_new.__singleton_wrapper__ = True
singleton_init.__singleton_wrapper__ = True
newClass.__new__ = singleton_new
newClass.__init__ = singleton_init
newClass.__singletonInstanceCond__ = Condition()
newClass.__singletonInstanceInit__ = True
newClass.__singletonInstanceCache__ = None
return True
return False
@classmethod
def _wrapNewMethodIfAbstract(metacls, newClass) -> bool:
"""
If the class has abstract methods, replace the ``_new__`` method, so it raises an exception.
:param newClass: The newly constructed class for further modifications.
:returns: ``True``, if the class is abstract.
:raises AbstractClassError: If the class is abstract and can't be instantiated.
"""
# Replace '__new__' by a variant to throw an error on not overridden methods
if len(newClass.__abstractMethods__) > 0:
oldnew = newClass.__new__
if hasattr(oldnew, "__raises_abstract_class_error__"):
oldnew = oldnew.__wrapped__
@wraps(oldnew)
def abstract_new(cls, *_, **__):
raise AbstractClassError(f"""Class '{cls.__name__}' is abstract. The following methods: '{"', '".join(newClass.__abstractMethods__)}' need to be overridden in a derived class.""")
abstract_new.__raises_abstract_class_error__ = True
newClass.__new__ = abstract_new
return True
# Handle classes which are not abstract, especially derived classes, if not abstract anymore
else:
# skip intermediate 'new' function if class isn't abstract anymore
try:
if newClass.__new__.__raises_abstract_class_error__:
origNew = newClass.__new__.__wrapped__
# WORKAROUND: __new__ checks tp_new and implements different behavior
# Bugreport: https://github.com/python/cpython/issues/105888
if origNew is object.__new__:
@wraps(object.__new__)
def wrapped_new(inst, *_, **__):
return object.__new__(inst)
newClass.__new__ = wrapped_new
else:
newClass.__new__ = origNew
elif newClass.__new__.__isSingleton__:
raise Exception(f"Found a singleton wrapper around an AbstractError raising method. This case is not handled yet.")
except AttributeError as ex:
# WORKAROUND:
# AttributeError.name was added in Python 3.10. For version <3.10 use a string contains operation.
try:
if ex.name != "__raises_abstract_class_error__":
raise ex
except AttributeError:
if "__raises_abstract_class_error__" not in str(ex):
raise ex
return False
# Additional properties and methods on a class
@readonly
def HasClassAttributes(self) -> bool:
"""
Read-only property to check if the class has Attributes (:attr:`__pyattr__`).
:returns: ``True``, if the class has Attributes.
"""
try:
return len(self.__pyattr__) > 0
except AttributeError:
return False
@readonly
def HasMethodAttributes(self) -> bool:
"""
Read-only property to check if the class has methods with Attributes (:attr:`__methodsWithAttributes__`).
:returns: ``True``, if the class has any method with Attributes.
"""
try:
return len(self.__methodsWithAttributes__) > 0
except AttributeError:
return False
@export
class SlottedObject(metaclass=ExtendedType, slots=True):
"""Classes derived from this class will store all members in ``__slots__``."""
|