简体   繁体   English

使用Python fn模块的函数

[英]Function currying with Python fn module

I found this functional programming library fn and I found the following code for function currying 我找到了该函数式编程库fn,并且发现了以下用于函数循环的代码

>>> from fn.func import curried
>>> @curried
... def sum5(a, b, c, d, e):
...     return a + b + c + d + e
...
>>> sum5(1)(2)(3)(4)(5)
15
>>> sum5(1, 2, 3)(4, 5)
15

but when I run it I get 但是当我运行它时,我得到了

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/adrian/.local/lib/python2.7/site-packages/fn/func.py", line 83, in _curried
    return curried(partial(func, *args, **kwargs))
  File "/home/adrian/.local/lib/python2.7/site-packages/fn/func.py", line 69, in curried
    @wraps(func)
  File "/usr/lib/python2.7/functools.py", line 33, in update_wrapper
    setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'functools.partial' object has no attribute '__module__'

Is it possible to solve this? 有可能解决这个问题吗?

wraps behaviour is different in python3 compared to python2 in particular `update_wrapper``, the code will work with python3 as is but you would need to use the wraps implementation from py3 for the it to work. python3中的wraps行为与python2特别是update_wrapper相比有所不同,该代码将按原样与python3一起工作,但您需要使用py3中的wraps实现才能正常工作。

I would file a bug report but in the mean time the relevant functions from functools are here: 我会提交一个错误报告,但与此同时,functools的相关功能在这里:

from functools import wraps, partial, WRAPPER_ASSIGNMENTS,WRAPPER_UPDATES
def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = WRAPPER_UPDATES):
    """Update a wrapper function to look like the wrapped function
       wrapper is the function to be updated
       wrapped is the original function
       assigned is a tuple naming the attributes assigned directly
       from the wrapped function to the wrapper function (defaults to
       functools.WRAPPER_ASSIGNMENTS)
       updated is a tuple naming the attributes of the wrapper that
       are updated with the corresponding attribute from the wrapped
       function (defaults to functools.WRAPPER_UPDATES)
    """
    for attr in assigned:
        try:
            value = getattr(wrapped, attr)
        except AttributeError:
            pass
        else:
            setattr(wrapper, attr, value)
    for attr in updated:
        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
    # Issue #17482: set __wrapped__ last so we don't inadvertently copy it
    # from the wrapped function when updating __dict__
    wrapper.__wrapped__ = wrapped
    # Return the wrapper so this can be used as a decorator via partial()
    return wrapper

def wraps(wrapped,
          assigned = WRAPPER_ASSIGNMENTS,
          updated = WRAPPER_UPDATES):
    """Decorator factory to apply update_wrapper() to a wrapper function
       Returns a decorator that invokes update_wrapper() with the decorated
       function as the wrapper argument and the arguments to wraps() as the
       remaining arguments. Default arguments are as for update_wrapper().
       This is a convenience function to simplify applying partial() to
       update_wrapper().
    """
    return partial(update_wrapper, wrapped=wrapped,
                   assigned=assigned, updated=updated)

The curried wrapper: 咖喱包装:

def curried(func):
    """A decorator that makes the function curried
    Usage example:
    >>> @curried
    ... def sum5(a, b, c, d, e):
    ...     return a + b + c + d + e
    ...
    >>> sum5(1)(2)(3)(4)(5)
    15
    >>> sum5(1, 2, 3)(4, 5)
    15
    """
    @wraps(func)
    def _curried(*args, **kwargs):
        f = func
        count = 0
        while isinstance(f, partial):
            print(f)
            if f.args:
                count += len(f.args)
            f = f.func

        spec = getargspec(f)

        if count == len(spec.args) - len(args):
            return func(*args, **kwargs)

        return curried(partial(func, *args, **kwargs))
    return _curried

To fix just the curried function for python2 you could only keep attrs from WRAPPER_ASSIGNMENTS that the func has: 要解决只是curried功能python2你只能保持ATTRS从WRAPPER_ASSIGNMENTS的FUNC有:

#change this line 

@wraps(func, (attr for attr in WRAPPER_ASSIGNMENTS if hasattr(func, attr)))
    def _curried(*args, **kwargs):
        f = func
        count = 0
        while isinstance(f, partial):
            print(f)
            if f.args:
                count += len(f.args)
            f = f.func

        spec = getargspec(f)

        if count == len(spec.args) - len(args):
            return func(*args, **kwargs)

        return curried(partial(func, *args, **kwargs))
    return _curried

Maybe you want to have a look at functools.partial . 也许您想看看functools.partial You can get rid of the annotation and just use 您可以摆脱注释,而只需使用

curried = partial(sum5, 2, 3, 4)
curried(5, 6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM