Skip to content

Instantly share code, notes, and snippets.

@dwf
Created January 28, 2016 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwf/e09a05fd6a8b907c59d5 to your computer and use it in GitHub Desktop.
Save dwf/e09a05fd6a8b907c59d5 to your computer and use it in GitHub Desktop.
functools.partial workalike where provided positionals are appended, not prepended.
import functools
class partial_last(functools.partial):
"""Like functools.partial, but fill positionals from the end.
Useful for builtin C functions where you *can't* pass later args as
keywords because CPython is stupid about that.
Examples
--------
>>> int_checker = partial_last(isinstance, int)
>>> int_checker(5)
True
>>> int_checker('Bob')
False
>>> foo_attr_getter = partial_last(getattr, 'foo', 'no way jose')
>>> class Bar(object):
... foo = 'yes sirree'
>>> foo_attr_getter(Bar())
'yes sirree'
>>> foo_attr_getter(6)
'no way jose'
"""
def __call__(self, *args, **kwargs):
all_kw = dict(self.keywords) if self.keywords is not None else {}
all_kw.update(kwargs)
return self.func(*(args + self.args), **all_kw)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment