Skip to content

Instantly share code, notes, and snippets.

@apua
Created October 23, 2022 14:12
Show Gist options
  • Save apua/babf110d2b5ae48846c8753f06686066 to your computer and use it in GitHub Desktop.
Save apua/babf110d2b5ae48846c8753f06686066 to your computer and use it in GitHub Desktop.
"""
file: /tmp/qwer.py
>>> @ensure_paths_exist
... def a(p: Path, *a, pp: Path): pass
...
>>> a('/tmp/qwer', pp='/tmp/qwer.py')
>>> a('/tmp/qwer.py', 1,2, pp='/tmp/qwer')
Traceback (most recent call last):
...
FileNotFoundError: No such file or directory: '/tmp/qwer'
"""
from pathlib import Path
def ensure_paths_exist(func):
"""
Ensure annotated paths exist.
"""
#print(dir(func))
#print(func.__annotations__)
path_keys = [k for k, t in func.__annotations__.items() if issubclass(t, Path)]
from functools import wraps
@wraps(func)
def _func(*a, **kw):
for k, v in kw.items():
if k in path_keys and not Path(v).exists():
raise FileNotFoundError(f'No such file or directory: {repr(v)}')
return func(*a, **kw)
#print(_func.__name__)
#print(_func.__doc__)
return _func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment