工具

tenacity 是一个通用的 retry 库,用于简化向任何任务加入重试的功能。

  1. import random
  2. from tenacity import retry
  3. @retry
  4. def do_something_unreliable():
  5. if random.randint(0, 10) > 1:
  6. raise IOError("Broken sauce, everything is hosed!!!111one")
  7. else:
  8. return "Awesome sauce!"
  9. print(do_something_unreliable())

JWT

python-jose

ORM

Tortoise ORM

日志

loguru

  1. from loguru import logger
  2. logger.debug("That's it, beautiful and simple logging!")

Logbook

Structlog

消息队列

Celery

RQ

相比 Celery 使用更简单

进程管理

supervisor

调试

PySnooper

  1. import pysnooper
  2. @pysnooper.snoop()
  3. def number_to_bits(number):
  4. if number:
  5. bits = []
  6. while number:
  7. number, remainder = divmod(number, 2)
  8. bits.insert(0, remainder)
  9. return bits
  10. else:
  11. return [0]
  12. number_to_bits(6)
  1. Starting var:.. number = 6
  2. 21:14:32.099769 call 3 @pysnooper.snoop()
  3. 21:14:32.099769 line 5 if number:
  4. 21:14:32.099769 line 6 bits = []
  5. New var:....... bits = []
  6. 21:14:32.099769 line 7 while number:
  7. 21:14:32.099769 line 8 number, remainder = divmod(number, 2)
  8. New var:....... remainder = 0
  9. Modified var:.. number = 3
  10. 21:14:32.099769 line 9 bits.insert(0, remainder)
  11. Modified var:.. bits = [0]
  12. 21:14:32.099769 line 7 while number:
  13. 21:14:32.099769 line 8 number, remainder = divmod(number, 2)
  14. Modified var:.. number = 1
  15. Modified var:.. remainder = 1
  16. 21:14:32.099769 line 9 bits.insert(0, remainder)
  17. Modified var:.. bits = [1, 0]
  18. 21:14:32.099769 line 7 while number:
  19. 21:14:32.099769 line 8 number, remainder = divmod(number, 2)
  20. Modified var:.. number = 0
  21. 21:14:32.099769 line 9 bits.insert(0, remainder)
  22. Modified var:.. bits = [1, 1, 0]
  23. 21:14:32.099769 line 7 while number:
  24. 21:14:32.099769 line 10 return bits
  25. 21:14:32.099769 return 10 return bits

科学计算

numpy

pandas

CuPy

CuPy 一个开源的基于 NVIDIA CUDA 的矩阵计算加速库。CuPy的接口与NumPy的高度兼容; 在大多数情况下,它可以作为一个简易替换。 所有你需要做的只是在你的 Python 代码将 numpy 更换为 cupy 。它支持各种方法,索引,数据类型,广播等等。

  1. >>> import cupy as cp
  2. >>> x = cp.arange(6).reshape(2, 3).astype('f')
  3. >>> x
  4. array([[ 0., 1., 2.],
  5. [ 3., 4., 5.]], dtype=float32)
  6. >>> x.sum(axis=1)
  7. array([ 3., 12.], dtype=float32)

Numba

Numba 是一个用于编译 Python 数组和数值计算函数的编译器,这个编译器能够大幅提高直接使用Python编写的函数的运算速度。Numba 使用LLVM编译器架构将纯Python代码生成优化过的机器码,通过一些添加简单的注解,将面向数组和使用大量数学的 Python代码优化到与 C,C++和 Fortran 类似的性能,而无需改变Python的解释器。Numba的主要特性:

  • 动态代码生成 (在用户偏爱的导入期和运行期)
  • 为CPU(默认)和GPU硬件生成原生的代码
  • 集成Python的科学软件栈(Numpy)

下面是使用 Numba优化的函数方法,将Numpy数组作为参数:

  1. from numba import jit
  2. import random
  3. @jit(nopython=True)
  4. def monte_carlo_pi(nsamples):
  5. acc = 0
  6. for i in range(nsamples):
  7. x = random.random()
  8. y = random.random()
  9. if (x ** 2 + y ** 2) < 1.0:
  10. acc += 1
  11. return 4.0 * acc / nsamples

Streamlit

Streamlit 构建自定义ML工具的最快方法。

  1. import streamlit as st
  2. x = st.slider('Select a value')
  3. st.write(x, 'squared is', x * x)

Metaflow

Metaflow 是和上面介绍的科学计算的库不同,它服务于数据科学家,目标是减轻非技术型数据科学家学习技术的负担,比如如何利用计算资源、怎么实现并行运算、架构设计、版本控制等,帮助提高数据科学家的生产率。
看下面的例子:借助 Metaflow 我们可以实现 Spark 中经典的 DAGs 计算流:
常用的库 - 图1

  1. from metaflow import FlowSpec, step
  2. class BranchFlow(FlowSpec):
  3. @step
  4. def start(self):
  5. self.next(self.a, self.b)
  6. @step
  7. def a(self):
  8. self.x = 1
  9. self.next(self.join)
  10. @step
  11. def b(self):
  12. self.x = 2
  13. self.next(self.join)
  14. @step
  15. def join(self, inputs):
  16. print('a is %s' % inputs.a.x)
  17. print('b is %s' % inputs.b.x)
  18. print('total is %d' % sum(input.x for input in inputs))
  19. self.next(self.end)
  20. @step
  21. def end(self):
  22. pass
  23. if __name__ == '__main__':
  24. BranchFlow()

爬虫

HTTPX

httpx 是高性能异步 HTTP 库,支持 HTTP/2 和 HTTP/1.1。API 设计参考 requests,简单易用。

  1. >>> import httpx
  2. >>> r = await httpx.get('https://httpbin.org/get')
  3. >>> r
  4. <Response [200 OK]>
  5. >>> r = await httpx.post('https://httpbin.org/post', data={'key': 'value'})
  6. >>> r = await httpx.put('https://httpbin.org/put', data={'key': 'value'})
  7. >>> r = await httpx.delete('https://httpbin.org/delete')
  8. >>> r = await httpx.head('https://httpbin.org/get')
  9. >>> r = await httpx.options('https://httpbin.org/get')

高性能

immutables 用于Python的高性能不可变映射类型。

  1. import immutables
  2. map = immutables.Map(a=1, b=2)
  3. print(map['a'])
  4. # will print '1'
  5. print(map.get('z', 100))
  6. # will print '100'
  7. print('z' in map)
  8. # will print 'False'

性能分析

memory_profiler

memory_profiler - 监视Python代码的内存使用情况。

  1. $ pip install -U memory_profiler
  2. $ python -m memory_profiler example.py
  3. Line # Mem usage Increment Occurences Line Contents
  4. ============================================================
  5. 3 38.816 MiB 38.816 MiB 1 @profile
  6. 4 def my_func():
  7. 5 46.492 MiB 7.676 MiB 1 a = [1] * (10 ** 6)
  8. 6 199.117 MiB 152.625 MiB 1 b = [2] * (2 * 10 ** 7)
  9. 7 46.629 MiB -152.488 MiB 1 del b
  10. 8 46.629 MiB 0.000 MiB 1 return a