Skip to content

Декоратор@hook

Initialize hook from callable/context manager.

.. versionadded:: 0.7.0

Examples

.. tabs::

.. code-tab:: py Decorate a function or generator

    from onetl.hooks import hook, HookPriority


    @hook
    def some_func(*args, **kwargs):
        ...


    @hook(enabled=True, priority=HookPriority.FIRST)
    def another_func(*args, **kwargs):
        ...

.. code-tab:: py Decorate a context manager

    from onetl.hooks import hook, HookPriority


    @hook
    class SimpleContextManager:
        def __init__(self, *args, **kwargs):
            ...

        def __enter__(self):
            ...
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            ...
            return False


    @hook(enabled=True, priority=HookPriority.FIRST)
    class ContextManagerWithProcessResult:
        def __init__(self, *args, **kwargs):
            ...

        def __enter__(self):
            ...
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            ...
            return False

        def process_result(self, result):
            # special method to handle method result call
            return modify(result)

        ...
Source code in onetl/hooks/hook.py
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
def hook(inp: Callable[..., T] | None = None, enabled: bool = True, priority: HookPriority = HookPriority.NORMAL):
    """
    Initialize hook from callable/context manager.

    .. versionadded:: 0.7.0

    Examples
    --------

    .. tabs::

        .. code-tab:: py Decorate a function or generator

            from onetl.hooks import hook, HookPriority


            @hook
            def some_func(*args, **kwargs):
                ...


            @hook(enabled=True, priority=HookPriority.FIRST)
            def another_func(*args, **kwargs):
                ...

        .. code-tab:: py Decorate a context manager

            from onetl.hooks import hook, HookPriority


            @hook
            class SimpleContextManager:
                def __init__(self, *args, **kwargs):
                    ...

                def __enter__(self):
                    ...
                    return self

                def __exit__(self, exc_type, exc_value, traceback):
                    ...
                    return False


            @hook(enabled=True, priority=HookPriority.FIRST)
            class ContextManagerWithProcessResult:
                def __init__(self, *args, **kwargs):
                    ...

                def __enter__(self):
                    ...
                    return self

                def __exit__(self, exc_type, exc_value, traceback):
                    ...
                    return False

                def process_result(self, result):
                    # special method to handle method result call
                    return modify(result)

                ...
    """

    def inner_wrapper(callback: Callable[..., T]):  # noqa: WPS430
        if isinstance(callback, Hook):
            raise TypeError("@hook decorator can be applied only once")

        result = Hook(callback=callback, enabled=enabled, priority=priority)
        return wraps(callback)(result)

    if inp is None:
        return inner_wrapper

    return inner_wrapper(inp)

Bases: int, Enum

Hook priority enum.

All hooks within the same priority are executed in the same order they were registered.

.. versionadded:: 0.7.0

Source code in onetl/hooks/hook.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class HookPriority(int, Enum):
    """
    Hook priority enum.

    All hooks within the same priority are executed in the same order they were registered.

    .. versionadded:: 0.7.0
    """

    FIRST = -1
    "Hooks with this priority will run first."

    NORMAL = 0
    "Hooks with this priority will run after :obj:`~FIRST` but before :obj:`~LAST`."

    LAST = 1
    "Hooks with this priority will run last."

FIRST = -1 class-attribute instance-attribute

Hooks with this priority will run first.

NORMAL = 0 class-attribute instance-attribute

Hooks with this priority will run after :obj:~FIRST but before :obj:~LAST.

LAST = 1 class-attribute instance-attribute

Hooks with this priority will run last.

Bases: Generic[T]

Hook representation.

.. versionadded:: 0.7.0

Parameters

callback : :obj:`typing.Callable`

    Some callable object which will be wrapped into a Hook, like function or ContextManager class.

enabled : bool

    Will hook be executed or not. Useful for debugging.

priority : :obj:`onetl.hooks.hook.HookPriority`

    Changes hooks priority, see ``HookPriority`` documentation.

Examples

.. code:: python

from onetl.hooks.hook import Hook, HookPriority


def some_func(*args, **kwargs): ...


hook = Hook(callback=some_func, enabled=True, priority=HookPriority.FIRST)
Source code in onetl/hooks/hook.py
 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
@dataclass  # noqa: WPS338
class Hook(Generic[T]):  # noqa: WPS338
    """
    Hook representation.

    .. versionadded:: 0.7.0

    Parameters
    ----------

        callback : :obj:`typing.Callable`

            Some callable object which will be wrapped into a Hook, like function or ContextManager class.

        enabled : bool

            Will hook be executed or not. Useful for debugging.

        priority : :obj:`onetl.hooks.hook.HookPriority`

            Changes hooks priority, see ``HookPriority`` documentation.

    Examples
    --------

    .. code:: python

        from onetl.hooks.hook import Hook, HookPriority


        def some_func(*args, **kwargs): ...


        hook = Hook(callback=some_func, enabled=True, priority=HookPriority.FIRST)
    """

    callback: Callable[..., T]
    enabled: bool = True
    priority: HookPriority = HookPriority.NORMAL

    def __post_init__(self):
        self.priority = HookPriority(self.priority)

    def enable(self):
        """
        Enable the hook.

        .. versionadded:: 0.7.0

        Examples
        --------

        >>> def func1(): ...
        >>> hook = Hook(callback=func1, enabled=False)
        >>> hook.enabled
        False
        >>> hook.enable()
        >>> hook.enabled
        True
        """
        if self.enabled:
            logger.log(
                NOTICE,
                "|Hooks| Hook '%s.%s' already enabled",
                self.callback.__module__,
                self.callback.__qualname__,
            )
        else:
            logger.log(NOTICE, "|Hooks| Enable hook '%s.%s'", self.callback.__module__, self.callback.__qualname__)
            self.enabled = True

    def disable(self):
        """
        Disable the hook.

        .. versionadded:: 0.7.0

        Examples
        --------

        >>> def func1(): ...
        >>> hook = Hook(callback=func1, enabled=True)
        >>> hook.enabled
        True
        >>> hook.disable()
        >>> hook.enabled
        False
        """
        if self.enabled:
            logger.log(NOTICE, "|Hooks| Disable hook '%s.%s'", self.callback.__module__, self.callback.__qualname__)
            self.enabled = False
        else:
            logger.log(
                NOTICE,
                "|Hooks| Hook '%s.%s' already disabled",
                self.callback.__module__,
                self.callback.__qualname__,
            )

    @contextmanager
    def skip(self):
        """
        Temporary disable the hook.

        .. note::

            If hook was created with ``enabled=False``, or was disabled by :obj:`~disable`,
            its state will left intact after exiting the context.

            You should call :obj:`~enable` explicitly to change its state.

        .. versionadded:: 0.7.0

        Examples
        --------

        .. tabs::

            .. tab:: Context manager syntax

                >>> def func1(): ...
                >>> hook = Hook(callback=func1, enabled=True)
                >>> hook.enabled
                True
                >>> with hook.skip():
                ...     print(hook.enabled)
                False
                >>> # hook state is restored as it was before entering the context manager
                >>> hook.enabled
                True

            .. tab:: Decorator syntax

                >>> def func1(): ...
                >>> hook = Hook(callback=func1, enabled=True)
                >>> hook.enabled
                True
                >>> @hook.skip()
                ... def hook_disabled():
                ...     print(hook.enabled)
                >>> hook_disabled()
                False
                >>> # hook state is restored as it was before entering the context manager
                >>> hook.enabled
                True
        """
        if not self.enabled:
            logger.log(
                NOTICE,
                "|Hooks| Hook '%s.%s' already disabled, nothing to skip",
                self.callback.__module__,
                self.callback.__qualname__,
            )
            yield
        else:
            logger.log(
                NOTICE,
                "|Hooks| Skipping hook '%s.%s' ...",
                self.callback.__module__,
                self.callback.__qualname__,
            )
            self.enabled = False

            yield

            logger.log(
                NOTICE,
                "|Hooks| Restoring hook '%s.%s' ...",
                self.callback.__module__,
                self.callback.__qualname__,
            )
            self.enabled = True

    def __call__(self, *args, **kwargs) -> T | ContextDecorator:
        """
        Calls the original callback with passed args.

        Examples
        --------

        >>> from onetl.hooks.hook import Hook, HookPriority
        >>> def some_func(*args, **kwargs):
        ...     print(args)
        ...     print(kwargs)
        ...     return "func result"
        >>> hook = Hook(callback=some_func)
        >>> result = hook(1, "abc", some="arg")
        (1, 'abc')
        {'some': 'arg'}
        >>> result
        'func result'
        """
        result = self.callback(*args, **kwargs)
        if isinstance(result, Generator):
            return ContextDecorator(result)
        return result

enable()

Enable the hook.

.. versionadded:: 0.7.0

Examples

def func1(): ... hook = Hook(callback=func1, enabled=False) hook.enabled False hook.enable() hook.enabled True

Source code in onetl/hooks/hook.py
 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
def enable(self):
    """
    Enable the hook.

    .. versionadded:: 0.7.0

    Examples
    --------

    >>> def func1(): ...
    >>> hook = Hook(callback=func1, enabled=False)
    >>> hook.enabled
    False
    >>> hook.enable()
    >>> hook.enabled
    True
    """
    if self.enabled:
        logger.log(
            NOTICE,
            "|Hooks| Hook '%s.%s' already enabled",
            self.callback.__module__,
            self.callback.__qualname__,
        )
    else:
        logger.log(NOTICE, "|Hooks| Enable hook '%s.%s'", self.callback.__module__, self.callback.__qualname__)
        self.enabled = True

disable()

Disable the hook.

.. versionadded:: 0.7.0

Examples

def func1(): ... hook = Hook(callback=func1, enabled=True) hook.enabled True hook.disable() hook.enabled False

Source code in onetl/hooks/hook.py
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
def disable(self):
    """
    Disable the hook.

    .. versionadded:: 0.7.0

    Examples
    --------

    >>> def func1(): ...
    >>> hook = Hook(callback=func1, enabled=True)
    >>> hook.enabled
    True
    >>> hook.disable()
    >>> hook.enabled
    False
    """
    if self.enabled:
        logger.log(NOTICE, "|Hooks| Disable hook '%s.%s'", self.callback.__module__, self.callback.__qualname__)
        self.enabled = False
    else:
        logger.log(
            NOTICE,
            "|Hooks| Hook '%s.%s' already disabled",
            self.callback.__module__,
            self.callback.__qualname__,
        )

skip()

Temporary disable the hook.

.. note::

If hook was created with ``enabled=False``, or was disabled by :obj:`~disable`,
its state will left intact after exiting the context.

You should call :obj:`~enable` explicitly to change its state.

.. versionadded:: 0.7.0

Examples

.. tabs::

.. tab:: Context manager syntax

    >>> def func1(): ...
    >>> hook = Hook(callback=func1, enabled=True)
    >>> hook.enabled
    True
    >>> with hook.skip():
    ...     print(hook.enabled)
    False
    >>> # hook state is restored as it was before entering the context manager
    >>> hook.enabled
    True

.. tab:: Decorator syntax

    >>> def func1(): ...
    >>> hook = Hook(callback=func1, enabled=True)
    >>> hook.enabled
    True
    >>> @hook.skip()
    ... def hook_disabled():
    ...     print(hook.enabled)
    >>> hook_disabled()
    False
    >>> # hook state is restored as it was before entering the context manager
    >>> hook.enabled
    True
Source code in onetl/hooks/hook.py
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
@contextmanager
def skip(self):
    """
    Temporary disable the hook.

    .. note::

        If hook was created with ``enabled=False``, or was disabled by :obj:`~disable`,
        its state will left intact after exiting the context.

        You should call :obj:`~enable` explicitly to change its state.

    .. versionadded:: 0.7.0

    Examples
    --------

    .. tabs::

        .. tab:: Context manager syntax

            >>> def func1(): ...
            >>> hook = Hook(callback=func1, enabled=True)
            >>> hook.enabled
            True
            >>> with hook.skip():
            ...     print(hook.enabled)
            False
            >>> # hook state is restored as it was before entering the context manager
            >>> hook.enabled
            True

        .. tab:: Decorator syntax

            >>> def func1(): ...
            >>> hook = Hook(callback=func1, enabled=True)
            >>> hook.enabled
            True
            >>> @hook.skip()
            ... def hook_disabled():
            ...     print(hook.enabled)
            >>> hook_disabled()
            False
            >>> # hook state is restored as it was before entering the context manager
            >>> hook.enabled
            True
    """
    if not self.enabled:
        logger.log(
            NOTICE,
            "|Hooks| Hook '%s.%s' already disabled, nothing to skip",
            self.callback.__module__,
            self.callback.__qualname__,
        )
        yield
    else:
        logger.log(
            NOTICE,
            "|Hooks| Skipping hook '%s.%s' ...",
            self.callback.__module__,
            self.callback.__qualname__,
        )
        self.enabled = False

        yield

        logger.log(
            NOTICE,
            "|Hooks| Restoring hook '%s.%s' ...",
            self.callback.__module__,
            self.callback.__qualname__,
        )
        self.enabled = True