Created
January 28, 2016 21:48
-
-
Save dwf/e09a05fd6a8b907c59d5 to your computer and use it in GitHub Desktop.
functools.partial workalike where provided positionals are appended, not prepended.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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