Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for decorative partial functions #150

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import inspect
import operator
import itertools
import functools
from contextlib import _GeneratorContextManager
from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction

Expand Down Expand Up @@ -71,7 +72,7 @@ def __init__(self, func=None, name=None, signature=None,
self.name = '_lambda_'
self.doc = func.__doc__
self.module = func.__module__
if inspect.isroutine(func):
if inspect.isroutine(func) or isinstance(func, functools.partial):
argspec = getfullargspec(func)
self.annotations = getattr(func, '__annotations__', {})
for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
Expand Down Expand Up @@ -214,6 +215,8 @@ def decorate(func, caller, extras=(), kwsyntax=False):
does. By default kwsyntax is False and the the arguments are untouched.
"""
sig = inspect.signature(func)
if isinstance(func, functools.partial):
func = functools.update_wrapper(func, func.func)
if iscoroutinefunction(caller):
async def fun(*args, **kw):
if not kwsyntax:
Expand All @@ -230,6 +233,7 @@ def fun(*args, **kw):
if not kwsyntax:
args, kw = fix(args, kw, sig)
return caller(func, *(extras + args), **kw)

fun.__name__ = func.__name__
fun.__doc__ = func.__doc__
fun.__wrapped__ = func
Expand Down
16 changes: 16 additions & 0 deletions src/tests/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import unittest
import decimal
import inspect
import functools
from asyncio import get_event_loop
from collections import defaultdict, ChainMap, abc as c
from decorator import dispatch_on, contextmanager, decorator
Expand Down Expand Up @@ -509,5 +510,20 @@ def __len__(self):
h(u)


@decorator
def partial_before_after(func, *args, **kwargs):
return "<before>" + func(*args, **kwargs) + "<after>"


class PartialTestCase(unittest.TestCase):
def test_before_after(self):
def origin_func(x, y):
return x + y
_func = functools.partial(origin_func, "x")
partial_func = partial_before_after(_func)
out = partial_func("y")
self.assertEqual(out, '<before>xy<after>')


if __name__ == '__main__':
unittest.main()