Skip to content
Snippets Groups Projects
Commit 1a1d9ac2 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

add execute_before

parent 3209c461
No related branches found
No related tags found
No related merge requests found
# v2.9.12
* added `execute_before`
......@@ -133,3 +133,8 @@ A ``functools.wraps()`` equivalent, but for classes
.. autofunction:: satella.coding.wraps
execute_before
--------------
.. autofunction:: satella.coding.decorators.execute_before
__version__ = '2.9.12_a1'
__version__ = '2.9.12_a2'
from .arguments import auto_adapt_to_methods, attach_arguments, for_argument
from .arguments import auto_adapt_to_methods, attach_arguments, for_argument, \
execute_before
from .decorators import wraps, queue_get, chain_functions, has_keys, short_none
from .preconditions import postcondition, precondition
__all__ = ['postcondition', 'precondition', 'wraps', 'queue_get', 'chain_functions',
__all__ = ['execute_before', 'postcondition', 'precondition', 'wraps', 'queue_get', 'chain_functions',
'has_keys', 'short_none', 'auto_adapt_to_methods', 'attach_arguments', 'for_argument']
......@@ -12,6 +12,43 @@ def _NOP(x):
return x
def execute_before(callable_: tp.Callable[[], None]):
"""
Wrapper to create wrappers which execute callable before function launch.
Use like this:
>>> @execute_before
>>> def do_things():
>>> print('Things are done')
Then the following will print 'Things are done'
>>> @do_things
>>> def nothing():
>>> ...
>>> nothing()
As well as the following:
>>> do_things(execute=True)
to simply execute the callable.
"""
def outer(fun=None, execute: bool = False):
if execute:
return callable_()
else:
@wraps(fun)
def inner(*args, **kwargs):
callable_()
return fun(*args, **kwargs)
return inner
return outer
def auto_adapt_to_methods(decorator):
"""
Allows you to use the same decorator on methods and functions,
......
......@@ -5,7 +5,8 @@ from socket import socket
from satella.coding import wraps, chain_functions, postcondition, \
log_exceptions, queue_get, precondition, short_none
from satella.coding.decorators import auto_adapt_to_methods, attach_arguments
from satella.coding.decorators import auto_adapt_to_methods, attach_arguments, \
execute_before
from satella.exceptions import PreconditionError
logger = logging.getLogger(__name__)
......@@ -13,6 +14,22 @@ logger = logging.getLogger(__name__)
class TestDecorators(unittest.TestCase):
def test_execute_before(self):
a = 0
@execute_before
def increase_a():
nonlocal a
a += 1
@increase_a
def launch_me():
nonlocal a
a += 1
launch_me()
self.assertEqual(a, 2)
def test_precondition_none(self):
@precondition(short_none('x == 2'))
def x(y):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment