Python标准库: functools (cmp_to_key, lru_cache, total_ordering, partial, partialmethod, reduce, singledispatch, update_wrapper, wraps)
functools模块处理的对象都是其他的函数,任何可调用对象都可以被视为用于此模块的函数。
1. functools.cmp_to_key(func)
因为Python3不支持比较函数,cmp_to_key就是将老式的比较函数(comparison function)转换成关键字函数(key function),与能够接受key function的函数一起使用,比如说sorted,list.sort, min, max, heapq.nlargest, itertools.groupby等等。
例子:
from functools import cmp_to_key
def compare(x1, x2):
return x1 - x2 a = [2, 3, 1]
print(sorted(a, key=cmp_to_key(compare)))
a.sort(key=cmp_to_key(compare))
print(a)
输出:
[1, 2, 3]
[1, 2, 3]
2. @functools.lru_cache(maxsize=128, typed=False)
lru_cache可以作为装饰器将函数计算耗时的结果缓存起来,用来节省时间。
由于是使用字典进行的缓存,因此函数的关键字参数和位置参数必须是可哈希的。
如果maxsize=None,禁用lru功能,并且缓存可以无限制的增长。
当maxsize为2的幂次方时,lru的性能最好。
如果将typed设置为true,将单独缓存不同类型的函数参数,比如F(3)和F(3.0)将被视为不同结果的不同调用。
cache_info()函数可以用来测量缓存的有效性和优化maxsize参数。该函数返回一个命中、未命中、maxSize和currSize的命名的元组。
例子:
from functools import lru_cache
@lru_cache(maxsize=32)
def get_pep(num):
resource = "http://www.python.org/dev/peps/pep-%04d/" % num
try:
with urllib.request.urlopen(resource) as s:
return s.read()
except urllib.error.HTTPError:
return "Not Found"
for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
pep = get_pep(n)
print(n, len(pep))
print(get_pep.cache_info())
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n - 2)
print([fib(n) for n in range(16)])
print(fib.cache_info())
3. @functools.total_ordering
指定一个已经定义了一个或者多个比较排序方法的类,这个类修饰器提供其余的方法。
这个类必须已经定义了__lt__(), __le__(), __gt__(), __ge__()中的一个,并且定义了__eq__()
from functools import total_ordering
@total_ordering
class Student:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@staticmethod
def _is_valid_operand(other):
return hasattr(other, "last_name") and hasattr(other, "first_name")
def __eq__(self, other):
if not self._is_valid_operand(other):
return NotImplemented
return ((self.last_name.lower(), self.first_name.lower()) ==
(other.last_name.lower(), other.first_name.lower()))
def __lt__(self, other):
if not self._is_valid_operand(other):
return NotImplemented
return ((self.last_name.lower(), self.first_name.lower()) <
(other.last_name.lower(), other.first_name.lower()))
a = Student(first_name="tom", last_name="hancs")
b = Student(first_name="tom", last_name="hancs")
print(a == b)
print(a <= b)
print(a >= b)
如果不使用total_ordering对装饰器进行装饰的话,使用<=或者>=会报错:
Traceback (most recent call last):
File "D:/LearnProject/performance/functools_test.py", line 33, in <module>
print(a <= b)
TypeError: '<=' not supported between instances of 'Student' and 'Student'
4. functools.partial(func, *args, **keywords)
partial()用于冻结函数参数或者关键的其中一部分,生成一个简化了参数传入的新的函数对象。
例子:
from functools import partial basetwo = partial(int, base=2)
print(basetwo('111'))
5. functools.partialmethod(func, *args, **keywords)
功能与partial类似,用法如下:
from functools import partialmethod
class Cell(object):
def __init__(self):
self._alive = False
@property
def alive(self):
return self._alive
def set_state(self, state):
self._alive = bool(state)
set_alive = partialmethod(set_state, True)
set_dead = partialmethod(set_state, False)
c = Cell()
print(c.alive)
c.set_alive()
print(c.alive)
6. reduce(function, iterable[,initializer])
将两个参数的函数从左到右累计应用于序列项,比如reduce(lambda x, y:x+y, [1, 2, 3, 4, 5]),相当于计算(((1+2)+3)+4)+5。
from functools import reduce
print(reduce(lambda x, y: x+y, range(0, 10)))
7. @functools.singledispatch
当有一个函数需要根据传入的变量的类型来判断需要输出的内容时,通常的做法是在函数内部使用大量的if/elif/else来解决问题。
这样做会使代码显得笨重,难以维护,也不便于扩展。
functools.singledispatch方法就是用于处理这个问题的
用法:
from functools import singledispatch
@singledispatch
def func(arg, verbose=False):
if verbose:
print("Let me just say,", end=" ")
print(arg)
@func.register(int)
def _(arg, verbose=False):
if verbose:
print("Strength in numbers, eh?", end=" ")
print(arg)
@func.register(list)
def _(arg, verbose=False):
if verbose:
print("Enumerate this:")
for i, elem in enumerate(arg):
print(i, elem)
def nothing(arg, verbose=False):
print("Nothing.")
func.register(type(None), nothing)
@func.register(float)
def fun_num(arg, verbose=False):
if verbose:
print("Half of your number:", end=" ")
print(arg / 2)
func("Hello, world.")
func("test.", verbose=True)
func(42, verbose=True)
func(["spam", "spam", "eggs", "spam"], verbose=True)
func(None)
func(1.23)
# 检查泛型函数将为给定类型选择哪个实现
print(func.dispatch(float))
print(func.dispatch(dict))
# 访问所有已经注册的实现
print(func.registry.keys())
print(func.registry[float])
8. functools.update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
用来更新被装饰函数的__name__,__doc__等信息,使其看起来像被装饰的函数
from functools import update_wrapper
def wrap(func):
def call_it(*args, **kwargs):
"""call it"""
return func(*args, **kwargs)
return call_it
@wrap
def hello():
"""say hello"""
print("hello world")
def wrap2(func):
def call_it2(*args, **kwargs):
"""call it2"""
return func(*args, **kwargs)
return update_wrapper(call_it2, func)
@wrap2
def hello2():
"""say hello2"""
print("hello world2")
print(hello.__name__)
print(hello.__doc__)
print(hello2.__name__)
print(hello2.__doc__)
9. @functools.wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
使用了wraps的装饰器可以保留被装饰函数的属性
from functools import wraps
def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
print("Calling decorated function")
return f(*args, **kwargs)
return wrapper
@my_decorator
def example():
"""Example Docstring"""
print("Called example function")
example()
print(example.__name__)
print(example.__doc__)
文章中的例子来自Python官方文档和网络。
Python标准库: functools (cmp_to_key, lru_cache, total_ordering, partial, partialmethod, reduce, singledispatch, update_wrapper, wraps)的更多相关文章
- python标准库--functools.partial
官方相关地址:https://docs.python.org/3.6/library/functools.html 一.简单介绍: functools模块用于高阶函数:作用于或返回其他函数的函 ...
- Python标准库笔记(9) — functools模块
functools 作用于函数的函数 functools 模块提供用于调整或扩展函数和其他可调用对象的工具,而无需完全重写它们. 装饰器 partial 类是 functools 模块提供的主要工具, ...
- 转--Python标准库之一句话概括
作者原文链接 想掌握Python标准库,读它的官方文档很重要.本文并非此文档的复制版,而是对每一个库的一句话概括以及它的主要函数,由此用什么库心里就会有数了. 文本处理 string: 提供了字符集: ...
- Python 标准库中的装饰器
题目描述 1.简单举例 Python 标准库中的装饰器 2.说说你用过的 Python 标准库中的装饰器 1. 首先,我们比较熟悉,也是比较常用的 Python 标准库提供的装饰器有:property ...
- Python标准库笔记(10) — itertools模块
itertools 用于更高效地创建迭代器的函数工具. itertools 提供的功能受Clojure,Haskell,APL和SML等函数式编程语言的类似功能的启发.它们的目的是快速有效地使用内存, ...
- python第六天 函数 python标准库实例大全
今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...
- Python 标准库一览(Python进阶学习)
转自:http://blog.csdn.net/jurbo/article/details/52334345 写这个的起因是,还是因为在做Python challenge的时候,有的时候想解决问题,连 ...
- python 标准库大全
python 标准库 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata:Unicode字符数据库 string ...
- Python标准库14 数据库 (sqlite3)
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python自带一个轻量级的关系型数据库SQLite.这一数据库使用SQL语言.S ...
随机推荐
- GSS4 D - Can you answer these queries IV
//给你一个序列,有两种操作: //1.给定x和y,将区间[x,y]内的数开方 //2.询问区间和 // // 因为一个longlong类型的数最多开6次方就变成了1,所以对于1操作,我们暴力修改, ...
- Mac 上 QuickTime Player 播放器以 1.1、1.2 倍速等更精确速度快进/快退播放的方法
苹果的 QuickTime Player 播放器上点击双箭头按钮可以用 2.4.8 倍的速度快进/快退播放视频,但是 2 倍速太快了,如果我想以 1.1.1.2 倍速这种更精确的速度控制视频播放呢?按 ...
- Jmeter 5.1实现图片上传接口测试
背景: 项目过程中需要抓取接口进行图片上传的接口测试,所有上传功能大同小异,无非就是参数内容不同,此处记录一下,为其他上传做一些参考 1.通过fiddler抓取到的参数如下: Content-Disp ...
- html5中progress/meter元素
html5中progress/meter元素 一.总结 一句话总结: progress元素:用来建立一个进度条 meter元素的作用:用来建立一个度量条,用来表示度量衡的评定 <progress ...
- 用java输出杨辉三角
杨辉三角:它的两个边都是1,内部其它都是肩上两个数的和 第一种: package aaa; public class YangHui { public static void main(String[ ...
- peomethues 参数设置 监控网站 /usr/local/prometheus-2.13.0.linux-amd64/prometheus --config.file=/usr/local/prometheus-2.13.0.linux-amd64/prometheus.yml --web.listen-address=:9999 --web.enable-lifecycle
probe_http_status_code{instance="xxxx",job="web_status"} probe_http_status_code{ ...
- go语言读写文件
package main import ( "fmt" "io/ioutil" "os" ) func main() { filename ...
- Apache log4j 1.2 - Short introduction to log4j
Apache log4j 1.2 - Short introduction to log4jhttps://logging.apache.org/log4j/1.2/manual.html log4j ...
- 完美解决Cannot download "https://github.com/sass/node-sass/releases/download/binding.nod的问题
①:例如很多人第一步就会这样做: 出现:Cannot download "https://github.com/sass/node-sass/releases/download/版本号/XX ...
- JS 数字相加出现多个小数的问题
今天在页面上用到了js进行小数相加119.01+0.01,结果大家都知道应该是:119.02的,然而结果是119..0200000…. ,莫名其妙的,还以为是我写的程序有问题,后来查了下才知道这是ja ...