Skip to content

Commit

Permalink
Add doc on defensive/optional usage
Browse files Browse the repository at this point in the history
  • Loading branch information
karlicoss committed Jan 6, 2020
1 parent 24c58e3 commit 68b66f2
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
28 changes: 28 additions & 0 deletions README.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,34 @@
" * https://marshmallow-annotations.readthedocs.io/en/latest/ext/namedtuple.html#namedtuple-type-api\n",
" * https://pypi.org/project/marshmallow-dataclass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Tips and tricks\n",
"## Optional dependency\n",
"You can benefit from `cachew` even if you don't want to bloat your app's dependencies. Just use the following snippet:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import cachew.misc\n",
"dmd(f\"\"\"```python\n",
"{inspect.getsource(cachew.misc.mcachew)}\n",
"```\"\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now you can use `@mcachew` in place of `@cachew`, and be certain things don't break if `cachew` is missing."
]
}
],
"metadata": {
Expand Down
15 changes: 15 additions & 0 deletions src/cachew/misc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# TODO Ideally, needs doublewraps as well?
def mcachew(*args, **kwargs):
"""
Stands for 'Maybe cachew'.
Defensive wrapper around @cachew to make it an optional dependency.
"""
try:
import cachew
except ModuleNotFoundError:
import warnings
warnings.warn('cachew library not found. You might want to install it to speed things up. See https://github.com/karlicoss/cachew')
return lambda orig_func: orig_func
else:
return cachew.cachew(*args, **kwargs)

13 changes: 13 additions & 0 deletions src/cachew/tests/test_cachew.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,3 +614,16 @@ def test_concurrent_reads(tmp_path: Path, fuzz_cachew_impl):
# should be pretty instantaneous
# if it takes more, most likely means that helper was called again
assert taken < 5


def test_mcachew(tmp_path: Path):
# TODO how to test for defensive behaviour?
from cachew.misc import mcachew

@mcachew(cache_path=tmp_path / 'cache')
def func() -> Iterator[str]:
yield 'one'
yield 'two'

assert list(func()) == ['one', 'two']
assert list(func()) == ['one', 'two']

0 comments on commit 68b66f2

Please sign in to comment.