Skip to content

Instantly share code, notes, and snippets.

@bsitruk
Last active July 30, 2019 08:20
Show Gist options
  • Select an option

  • Save bsitruk/55983a79d6b8210a7c246e023cc7a2d8 to your computer and use it in GitHub Desktop.

Select an option

Save bsitruk/55983a79d6b8210a7c246e023cc7a2d8 to your computer and use it in GitHub Desktop.
Some functional utilities in python.
from tempfile import NamedTemporaryFile, TemporaryDirectory
def compose(g, f):
"""Right to left function composition."""
return lambda *args, **kwargs: g(f(*args, **kwargs))
def temporarify(action, directory=False):
"""
Generate a temporaryfied version of the action providing him a temporary file or folder that will be deleted
at the end of the operation.
:param action: The action method to perform - The first param will arg will be the temporary file/folder
:param directory: If True, a temporary directory will be used (default False)
:return: The temporaryfied action
"""
def tmp_action(*args, **kwargs):
temp_gen = TemporaryDirectory if directory else NamedTemporaryFile
with temp_gen() as tmp:
return action(getattr(tmp, 'name', tmp), *args, **kwargs)
return tmp_action
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment