itertools.accumulate() versus functools.reduce()

It seems that accumulate keeps the previous results, whereas reduce (which is known as fold in other languages) does not necessarily. e.g. list(accumulate([1,2,3], operator.add)) would return [1,3,6] whereas a plain fold would return 6 Also (just for fun, don’t do this) you can define accumulate in terms of reduce def accumulate(xs, f): return reduce(lambda a, … Read more

Use functools’ @lru_cache without specifying maxsize parameter

You have to at least call lru_cache without args: @lru_cache() def f(): #content of the function This way, lru_cache is initialized with default parameters. This is because decorators in python (with the @ notation) are special functions which are evaluated and called when the interpreter is importing the module. When you write @decorator_name you tell … Read more

python equivalent of functools ‘partial’ for a class / constructor

I don’t think there’s a standard method to do it, but if you need it often, you can just put together your own small function: import functools import collections def partialclass(cls, *args, **kwds): class NewCls(cls): __init__ = functools.partialmethod(cls.__init__, *args, **kwds) return NewCls if __name__ == ‘__main__’: Config = partialclass(collections.defaultdict, list) assert isinstance(Config(), Config)

functools.partial on class method

You are creating partials on the function, not the method. functools.partial() objects are not descriptors, they will not themselves add the self argument and cannot act as methods themselves. You can only wrap bound methods or functions, they don’t work at all with unbound methods. This is documented: partial objects are like function objects in … Read more

Make @lru_cache ignore some of the function arguments

With cachetools you can write: from cachetools import cached from cachetools.keys import hashkey from random import randint @cached(cache={}, key=lambda db_handle, query: hashkey(query)) def find_object(db_handle, query): print(“processing {0}”.format(query)) return query queries = list(range(5)) queries.extend(range(5)) for q in queries: print(“result: {0}”.format(find_object(randint(0, 1000), q))) You will need to install cachetools (pip install cachetools). The syntax is: @cached( cache={}, … Read more

Python functools lru_cache with instance methods: release object

This is not the cleanest solution, but it’s entirely transparent to the programmer: import functools import weakref def memoized_method(*lru_args, **lru_kwargs): def decorator(func): @functools.wraps(func) def wrapped_func(self, *args, **kwargs): # We’re storing the wrapped method inside the instance. If we had # a strong reference to self the instance would never die. self_weak = weakref.ref(self) @functools.wraps(func) @functools.lru_cache(*lru_args, … Read more

How does functools partial do what it does?

Roughly, partial does something like this (apart from keyword args support etc): def partial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper So, by calling partial(sum2, 4) you create a new function (a callable, to be precise) that behaves like sum2, but has one positional argument less. That missing argument is always … Read more

What does functools.wraps do?

When you use a decorator, you’re replacing one function with another. In other words, if you have a decorator def logged(func): def with_logging(*args, **kwargs): print(func.__name__ + ” was called”) return func(*args, **kwargs) return with_logging then when you say @logged def f(x): “””does some math””” return x + x * x it’s exactly the same as … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)