Skip to content

Commit

Permalink
Refactor as 'bypass_when' and 'bypass_unless' because one is likely m…
Browse files Browse the repository at this point in the history
…uch more useful to the caller than the other.
  • Loading branch information
jaraco committed May 29, 2023
1 parent 1ca6d75 commit 7876037
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
2 changes: 1 addition & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
v3.7.0
======

Added ``bypass_unless``.
Added ``bypass_unless`` and ``bypass_when`` and ``identity``.

v3.6.0
======
Expand Down
41 changes: 32 additions & 9 deletions jaraco/functools.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import collections
import functools
import time
import inspect
import collections
import types
import itertools
import operator
import time
import types
import warnings

import more_itertools
Expand Down Expand Up @@ -556,27 +557,49 @@ def wrapper(*args, **kwargs):
return decorate


def bypass_unless(check):
def identity(x):
return x


def bypass_when(check, *, _op=identity):
"""
Decorate a function to return its parameter unless ``check``.
Decorate a function to return its parameter when ``check``.
>>> enabled = [object()] # True
>>> bypassed = [] # False
>>> @bypass_unless(enabled)
>>> @bypass_when(bypassed)
... def double(x):
... return x * 2
>>> double(2)
4
>>> del enabled[:] # False
>>> bypassed[:] = [object()] # True
>>> double(2)
2
"""

def decorate(func):
@functools.wraps(func)
def wrapper(param):
return func(param) if check else param
return param if _op(check) else func(param)

return wrapper

return decorate


def bypass_unless(check):
"""
Decorate a function to return its parameter unless ``check``.
>>> enabled = [object()] # True
>>> @bypass_unless(enabled)
... def double(x):
... return x * 2
>>> double(2)
4
>>> del enabled[:] # False
>>> double(2)
2
"""
return bypass_when(check, _op=operator.not_)

0 comments on commit 7876037

Please sign in to comment.