Skip to content

Instantly share code, notes, and snippets.

@crowsonkb
Created December 16, 2018 03:14
Show Gist options
  • Save crowsonkb/6f13f995589cd4f9bafd04229d76afba to your computer and use it in GitHub Desktop.
Save crowsonkb/6f13f995589cd4f9bafd04229d76afba to your computer and use it in GitHub Desktop.
Captures and returns an argument passed to a lambda expression.
"""Captures and returns an argument passed to a lambda expression."""
class Capture:
"""Captures and returns an argument passed to a lambda expression.
:param fn: The lambda expression.
:type fn: function
:Example:
>>> from functools import reduce
>>> f = Capture(lambda x, y: x.append(y))[0]
>>> f([], 1)
[1]
>>> reduce(f, range(10), [])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
def __init__(self, fn):
self.fn = fn
def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs)
def __getitem__(self, key):
if not isinstance(key, (int, str)):
raise TypeError('index/key must be int or str, not ' + type(key).__name__)
def inner_fn(*args, **kwargs):
self(*args, **kwargs)
return args[key] if isinstance(key, int) else kwargs[key]
return inner_fn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment