标签: functools

为什么要在 Python 中设置部分对象的 __doc__ ?

help()不显示__doc__部分对象的。然而,文档中的示例设置了它:

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
Run Code Online (Sandbox Code Playgroud)

__doc__如果没有帮助,为什么要设置?

python functools

5
推荐指数
1
解决办法
707
查看次数

functools.partial和generator

我正在尝试执行以下操作:

import functools

class TestClass():
    def method(self, n):
        for i in xrange(n):
            yield i

# This works 
for x in TestClass().method(10):
    print x

# This gets a TypeError: functools.partial object not iterable
for x in functools.partial(TestClass().method, 10):
    print x
Run Code Online (Sandbox Code Playgroud)

那有什么不对?

python generator functools

5
推荐指数
1
解决办法
1576
查看次数

Python functools.lru_cache 驱逐回调或等效函数

是否可以定义functools.lru_cache一个项目被驱逐时的回调?在回调中还应该存在缓存的值。

如果没有,也许有人知道一个支持驱逐和回调的轻量级类似字典的缓存?

python python-3.x functools

5
推荐指数
1
解决办法
2495
查看次数

为什么我的LRU缓存缺少相同的参数?

我有一些看起来像这样的代码:

from functools import lru_cache


@lru_cache()
def get_cheese(type):
    print('{}? We\'re all out.'.format(type))
    return None

get_cheese(type='cheddar')
get_cheese('cheddar')
print(get_cheese.cache_info())
Run Code Online (Sandbox Code Playgroud)

cache_info()报告有两个遗漏-但是我使用相同的参数调用了该函数。

它实际上需要做一些事情,但我发现这是因为在一种情况下,我使用了关键字arg,而另一种情况下,我使用了位置参数。

但是为什么呢?

python caching functools

5
推荐指数
1
解决办法
367
查看次数

将itertools用于具有依赖关系的不同范围的任意数量的嵌套循环?

给出一个上限列表:B1,B2,... BN;
依赖函数:f1,...,fN-1,

我想知道是否有一个使用itertools或python中的其他类的配方:

for i1 in range(0, B1):  
    for i2 in range(f1(i1), B2): ...
         for iN in range(fN-1(iN-1), BN)
             dostuff(i1, i2, ... iN)
Run Code Online (Sandbox Code Playgroud)

哪里有N级筑巢?
我想使用这样的辅助函数:
dependentProducts(Bs,fs,dostuff),
它返回一个列表或者可迭代的

理想情况下,实现将是迭代而不是递归.

python python-itertools python-3.x functools

5
推荐指数
0
解决办法
218
查看次数

使用functools的@lru_cache而不指定maxsize参数

给出函数定义的文档lru_cache:

@functools.lru_cache(maxsize=128, typed=False)
Run Code Online (Sandbox Code Playgroud)

这对我说maxsize是可选的.

但是,它不喜欢没有参数调用:

Python 3.6.3 (default, Oct 24 2017, 14:48:20) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import functools
>>> @functools.lru_cache
... def f(): ...
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/functools.py", line 477, in lru_cache
    raise TypeError('Expected maxsize to be an integer or None')
TypeError: Expected maxsize to be an integer or None
 >>> 
Run Code Online (Sandbox Code Playgroud)

使用参数调用很好:

>>> @functools.lru_cache(8)
... …
Run Code Online (Sandbox Code Playgroud)

python caching lru functools

5
推荐指数
2
解决办法
2495
查看次数

使用 python3.7 在 ubuntu 16.04 上安装 python functools32 时出错

我尝试在 ubuntu 16.04 机器上安装 python functools 并收到此错误

Collecting functools32
  Downloading https://files.pythonhosted.org/packages/c5/60/6ac26ad05857c601308d8fb9e87fa36d0ebf889423f47c3502ef034365db/functools32-3.2.3-2.tar.gz
    Complete output from command python setup.py egg_info:
    This backport is for Python 2.7 only.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-a7fm4qrj/functools32/
Run Code Online (Sandbox Code Playgroud)

我还尝试从github 链接安装。结果还是失败了。出现以下错误。

Collecting git+https://github.com/michilu/python-functools32.git
  Cloning https://github.com/michilu/python-functools32.git to /tmp/pip-req-build-gyj6sclc
    Complete output from command python setup.py egg_info:
    This backport is for Python 2.7 only.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-req-build-gyj6sclc/
Run Code Online (Sandbox Code Playgroud)

我如何克服这个问题并安装 functools?

提前致谢

python-3.x functools

5
推荐指数
1
解决办法
7989
查看次数

Python库函数不带关键字参数

当我尝试对python中的问题应用更具功能性的方法时,就会出现此问题。我试图做的只是简单地将一个数字列表平方,没什么大不了的。

from operator import pow
from functools import partial 

squared = list(map(partial(pow, b=2), range(10))
Run Code Online (Sandbox Code Playgroud)

事实证明,这没有用。 TypeError: pow() takes no keyword arguments

困惑我检查是否pow(b=2, a=3)。没有。

我已经检查了操作员的源代码,没有可疑之处。

感到困惑,我开始怀疑自己的python知识,我自己做了一个pow函数。

def pow(a, b):
  return a ** b
Run Code Online (Sandbox Code Playgroud)

然后,我尝试用我的功能做同样的事情,而且令人惊讶的是,一切正常。

我不会猜测问题的原因是什么,我要问的仅仅是原因为何,以及是否存在解决方法。

python functional-programming keyword-argument functools

5
推荐指数
1
解决办法
87
查看次数

如何使用 Python reduce 或列表理解将函数列表按顺序应用于字符串?

问题陈述

我想将函数列表fs = [ f, g, h ]按顺序应用于字符串text=' abCdEf '

就像是f( g( h( text) ) )

这可以通过以下代码轻松完成:

# initial text
text = '  abCDef   '

# list of functions to apply sequentially
fs = [str.rstrip, str.lstrip, str.lower]

for f in fs:
    text = f(text)

# expected result is 'abcdef' with spaces stripped, and all lowercase
print(text)
Run Code Online (Sandbox Code Playgroud)

使用 functools.reduce

似乎functools.reduce应该在这里完成工作,因为它在每次迭代时“消耗”函数列表。

from functools import reduce

# I know `reduce` requires two arguments, but I don't …
Run Code Online (Sandbox Code Playgroud)

python reduce list-comprehension fold functools

5
推荐指数
1
解决办法
1076
查看次数

functools.singledispatchmethod with own class as arg type

I would like to use functools.singledispatchmethod to overload the binary arithmetic operator methods of a class called Polynomial. The problem I have is that I can't find a way to register method calls where other is a Polynomial.

Perhaps better explained with a simple example:

from __future__ import annotations
from functools import singledispatchmethod


class Polynomial:
    @singledispatchmethod
    def __add__(self, other):
        return NotImplemented

    @__add__.register
    def _(self, other: Polynomial):
        return NotImplemented
Run Code Online (Sandbox Code Playgroud)

The code above raises a NameError:

NameError: name 'Polynomial' is …
Run Code Online (Sandbox Code Playgroud)

python single-dispatch functools

5
推荐指数
1
解决办法
775
查看次数