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
|
.. _DECO:
Overview
########
The :mod:`pyTooling.Decorators` package provides decorators to:
* mark functions or methods as *not implemented*.
* control the visibility of classes and functions defined in a module.
* help with copying doc-strings from base-classes.
.. #contents:: Table of Contents
:depth: 2
.. _DECO/Abstract:
Abstract Methods
################
.. grid:: 2
.. grid-item::
:columns: 6
.. todo::
DECO:: Refer to :func:`~pyTooling.MetaClasses.abstractmethod` and :func:`~pyTooling.MetaClasses.mustoverride`
decorators from :ref:`meta classes <META>`.
.. important::
Classes using method decorators :ref:`@abstractmethod <DECO/AbstractMethod>` or
:ref:`@mustoverride <DECO/MustOverride>` need to use the meta-class :ref:`ExtendedType <META/ExtendedType>`.
Alternatively, classes can be derived from :ref:`SlottedObject <META/SlottedObject>` or apply decorators
:ref:`DECO/slotted` or :ref:`DECO/mixin`.
.. _DECO/AbstractMethod:
@abstractmethod
***************
.. grid:: 2
.. grid-item::
:columns: 6
The :func:`~pyTooling.MetaClasses.abstractmethod` decorator marks a method as *abstract*.
The original method gets replaced by a method raising a :exc:`NotImplementedError`. This can happen, if an
abstract method is overridden but called via :pycode:`super()...`.
When a class containing *abstract* methods is instantiated, an :exc:`~pyTooling.Exceptions.AbstractClassError` is raised.
.. hint::
If the abstract method contains code that should be called from an overriding method in a derived class, use the
:ref:`@mustoverride <DECO/MustOverride>` decorator.
.. important::
The class declaration must apply the metaclass :ref:`ExtendedType <META/ExtendedType>` so the decorator has an
effect.
.. grid-item::
:columns: 6
.. code-block:: Python
class A(metaclass=ExtendedType):
@abstractmethod
def method(self) -> int:
"""Methods documentation."""
class B(A):
@InheritDocString(A)
def method(self) -> int:
return 2
.. _DECO/MustOverride:
@mustoverride
*************
.. grid:: 2
.. grid-item::
:columns: 6
The :func:`~pyTooling.MetaClasses.mustoverride` decorator marks a method as *must override*.
When a class containing *must override* methods is instantiated, an :exc:`~pyTooling.Exceptions.MustOverrideClassError`
is raised.
In contrast to :ref:`@abstractmethod <DECO/AbstractMethod>`, the method can still be called from a derived class
implementing an overridden method.
.. hint::
If the method contain no code and if it should throw an exception when called, use the
:ref:`@abstractmethod <DECO/AbstractMethod>` decorator.
.. important::
The class declaration must apply the metaclass :ref:`ExtendedType <META/ExtendedType>` so the decorator has an
effect.
.. grid-item::
:columns: 6
.. code-block:: Python
class A(metaclass=ExtendedType):
@mustoverride
def method(self) -> int:
"""Methods documentation."""
return 2
class B(A):
@InheritDocString(A)
def method(self) -> int:
result = super().method()
return result + 1
.. _DECO/DataAccess:
Data Access
###########
.. _DECO/readonly:
@readonly
*********
.. grid:: 2
.. grid-item::
:columns: 6
The :func:`~pyTooling.Decorators.readonly` decorator makes a property *read-only*. Thus the properties
:pycode:`setter` and :pycode:`deleter` can't be used.
.. grid-item::
:columns: 6
.. code-block:: Python
class Data:
_data: int
def __init__(self, data: int) -> None:
self._data = data
@readonly
def Length(self) -> int:
return 2 ** self._data
.. _DECO/classproperty:
@classproperty
**************
.. grid:: 2
.. grid-item::
:columns: 6
.. attention:: Class properties are currently broken in Python.
.. _DECO/Documentation:
Documentation
#############
.. _DECO/export:
@export
*******
.. grid:: 2
.. grid-item::
:columns: 6
The :func:`~pyTooling.Decorators.export` decorator makes module's entities (classes and functions) publicly
visible. Therefore, these entities get registered in the module's variable ``__all__``.
Besides making these entities accessible via ``from foo import *``, Sphinx extensions like autoapi are reading
``__all__`` to infer what entities from a module should be auto documented.
.. grid-item::
:columns: 6
.. code-block:: Python
# Creating __all__ is only required, if variables need to be listed too
__all__ = ["MY_CONST"]
# Decorators can't be applied to fields, so it was manually registered in __all__
MY_CONST = 42
@export
class MyClass:
"""This is a public class."""
@export
def myFunc():
"""This is a public function."""
# Each application of "@export" will append an entry to __all__
.. #admonition:: ``application.py``
.. code-block:: python
from .module import *
inst = MyClass()
.. _DECO/InheritDocString:
@InheritDocString
*****************
.. grid:: 2
.. grid-item::
:columns: 6
When a method in a derived class shall have the same doc-string as the doc-string of the base-class, then the
decorator :func:`~pyTooling.Decorators.InheritDocString` can be used to copy the doc-string from base-class'
method to the method in the derived class.
.. grid-item::
:columns: 6
.. tab-set::
.. tab-item:: Inherit class documentation
.. code-block:: Python
class BaseClass:
"""Method's doc-string."""
@InheritDocString(BaseClass, merge=True)
class DerivedClass(BaseClass):
"""Will ne written underneath"""
.. tab-item:: Inherit method documentation
.. code-block:: Python
class BaseClass:
def method(self):
"""Method's doc-string."""
class DerivedClass(BaseClass):
@InheritDocString(BaseClass)
def method(self):
pass
.. _DECO/Performance:
Performance
###########
.. _DECO/slotted:
@slotted
********
.. grid:: 2
.. grid-item::
:columns: 6
The size of class instances (objects) can be reduced by using :ref:`slots`. This decreases the object creation
time and memory footprint. In addition access to fields faster because there is no time consuming field lookup in
``__dict__``. A class with 2 ``__dict__`` members has around 520 B whereas the same class structure uses only
around 120 B if slots are used. On CPython 3.10 using slots, the code accessing class fields is 10..25 % faster.
The :class:`~pyTooling.MetaClasses.ExtendedType` meta-class can automatically infer slots from type annotations.
Because the syntax for applying a meta-class is quite heavy, this decorator simplifies the syntax.
.. grid-item::
:columns: 6
.. tab-set::
.. tab-item:: Syntax using Decorator ``slotted``
.. code-block:: Python
@export
@slotted
class A:
_field1: int
_field2: str
def __init__(self, arg1: int, arg2: str) -> None:
self._field1 = arg1
self._field2 = arg2
.. tab-item:: Syntax using meta-class ``ExtendedType``
.. code-block:: Python
@export
class A(metaclass=ExtendedType, slots=True):
_field1: int
_field2: str
def __init__(self, arg1: int, arg2: str) -> None:
self._field1 = arg1
self._field2 = arg2
.. _DECO/mixin:
@mixin
******
.. grid:: 2
.. grid-item::
:columns: 6
The size of class instances (objects) can be reduced by using :ref:`slots` (see :ref:`DECO/slotted`). If slots are
used in multiple inheritance scenarios, only one ancestor line can use slots. For other ancestor lines, it's
allowed to define the slot fields in the inheriting class. Therefore pyTooling allows marking classes as
:term:`mixin-classes <mixin-class>`.
The :class:`~pyTooling.MetaClasses.ExtendedType` meta-class can automatically infer slots from type annotations.
If a class is marked as a mixin-class, the inferred slots are collected and handed over to class defining slots.
Because the syntax for applying a meta-class is quite heavy, this decorator simplifies the syntax.
.. grid-item::
:columns: 6
.. tab-set::
.. tab-item:: Syntax using Decorator ``mixin``
.. code-block:: Python
@export
@slotted
class A:
_field1: int
_field2: str
def __init__(self, arg1: int, arg2: str) -> None:
self._field1 = arg1
self._field2 = arg2
@export
class B(A):
_field3: int
_field4: str
def __init__(self, arg1: int, arg2: str) -> None:
self._field3 = arg1
self._field4 = arg2
super().__init__(arg1, arg2)
@export
@mixin
class C(A):
_field5: int
_field6: str
def Method(self) -> str:
return f"{self._field5} -> {self._field6}"
@export
class D(B, C):
def __init__(self, arg1: int, arg2: str) -> None:
super().__init__(arg1, arg2)
.. tab-item:: Syntax using meta-class ``ExtendedType``
.. code-block:: Python
@export
class A(metaclass=ExtendedType, slots=True):
_field1: int
_field2: str
def __init__(self, arg1: int, arg2: str) -> None:
self._field1 = arg1
self._field2 = arg2
@export
class B(A):
_field3: int
_field4: str
def __init__(self, arg1: int, arg2: str) -> None:
self._field3 = arg1
self._field4 = arg2
super().__init__(arg1, arg2)
@export
class C(A, mixin=True):
_field5: int
_field6: str
def Method(self) -> str:
return f"{self._field5} -> {self._field6}"
@export
class D(B, C):
def __init__(self, arg1: int, arg2: str) -> None:
super().__init__(arg1, arg2)
.. _DECO/singleton:
@singleton
**********
.. grid:: 2
.. grid-item::
:columns: 6
.. todo:: DECO::singleton needs documentation
.. _DECO/Misc:
Miscellaneous
#############
.. _DECO/notimplemented:
@notimplemented
***************
.. grid:: 2
.. grid-item::
:columns: 6
The :func:`~pyTooling.Decorators.notimplemented` decorator replaces a callable (function or method) with a
callable raising a :exc:`NotImplementedError` containing the decorators message parameter as an error message.
The original callable might contain code, but it's made unreachable by the decorator. The callable's name and
doc-string is copied to the replacing callable. A reference to the original callable is preserved in the
:pycode:`<callable>.__orig_func__` field.
.. grid-item::
:columns: 6
.. code-block:: Python
class Data:
@notimplemented("This function isn't tested yet.")
def method(self, param: int):
return 2 ** param
|