开发者

Error in imitating memoize() from django.utils.functional.py

开发者 https://www.devze.com 2022-12-15 03:51 出处:网络
def a(): print \'aa\' def b(): print \'bb\' def c(*x): print x def d(x,y): c(*(x+y)) d(a,b) Traceback (most recent call last):
def a():
    print 'aa'
def b():
    print 'bb'

def c(*x):
    print x

def d(x,y):
    c(*(x+y))

d(a,b)

Traceback (most recent call last):
  File "D:\zjm_code\mysite\zjmbooks\a.py", line 15, in <module>
    d(a,b)
  File "D:\zjm_code\mysite\zjmbooks\a.py", line 13, in d
    c(*(x+y))
TypeError: unsupported operand type(s) for +: 'function' and 'function'

the code in django.utils.functional.py:

def curry(_curried_func, *args, **kwargs):
    def _curried(*moreargs, **morekwargs):
        return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
    return _curried

WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = WRAPPER_UPDATES):
    for attr in assigned:
        try:
            setattr(wrapper, attr, getattr(wrapped, attr))
        except TypeError: # Python 2.3 doesn't allow assigning to __name__.
            pass
    for attr in updated:
        getattr(wrapper, attr).update(getattr(wrapped, attr))
    return wrapper

def wraps(wrapped,
          assigned = WRAPPER_ASSIGNMENTS,
          updated = WRAPPER_UPDATES):
    return curry(update_wrapper, wrapped=wrapped,
                 assigned=assigned, updated=updated)

### End from Python 2.5 functools.py ##########################################

def memoize(func, cache, num_args):
    def wrapper(*args):
        mem_args = args[:num_args]
        if mem_args in cache:
            return cache[mem_args]
        result = func(*args)
        cache[mem_args] = result
        return result
    return wraps(func)(wrapper)

my Analysis:

def curry(update_wrapper, *args, **kwargs):
    def _curried(*wrapper, **morekwargs):
        return update_wrapper(wrapper,{wrapped:func})#this is the result
    return _curried
def update_wrapper(wrapper,wrapped)

def wraps(func):
    return curry(u开发者_运维技巧pdate_wrapper, wrapped=func)

wraps(func)(wrapper)


Your code (in x+y, where x is a and y is b) is trying to sum two functions (instead of calling them and summing their results, for example): function objects cannot be summed, so your code raises an exeption.

The code you quote, in args+moreargs, is summing two tuples: tuples can of course perfectly well be summed, it means concatenating them. Absolutely no relation whatsoever to the absurd "sum of two functions" your code is attempting.

0

精彩评论

暂无评论...
验证码 换一张
取 消