ExpertPythonProgramming,2ndEdition(读书笔记,似乎对Python3.5并未着墨强调,但是代码示例容易看懂一点)
作者:想想以前哦 | 来源:互联网 | 2023-05-19 05:20
ExpertPythonProgramming,2ndEdition目录1Python当前状态2
Expert Python Programming, 2nd Edition
- 1 Python当前状态
- 2 语法最佳实践:class级别以下
- 3 语法最佳实践:class级别以上
- 4 选择好的名字
- 5 Writing a Package
- 6 部署代码
- 7 用其他语言写Python扩展
- 8 管理代码
- 9 项目文档
- 10 TDD
- 11 优化:一般原则和性能分析技术
- 12 优化:一些强大的技术
- 13 并发
- 14 有用的设计模式
Python当前状态
- Python 3 Wall of Superpowers https://python3wos.appspot.com
- Python 3主要语法修改:
- print:语句 => 函数
- 异常:except ex, e => except ex as e
- <>不相等比较 => !=
- 不允许在函数中执行from module import *(降低了动态性?)
- sort()不接受cmp参数,只允许指定key(见鬼,不支持纯FP风格?)
- 浮点数模运算:5.0//2.0 == 2.0
- from __future__ import
- PyPy:Python in Python,可以在运行时改变解释器的行为
- 3.4+:$ python -m ensurepip
- 环境隔离(依赖包的污染问题):virtualenv(依赖于文件系统)、venv、buildout
- 3.3+:pyvenv ENV
- buildout:自启动+部署
- vagrant
- Containerization versus virtualization
- Custom Python shells – IPython, bpython, ptpython, and so on
语法最佳实践:class级别以下
- CPython里的list实际上是用变长数组实现的
- for i, element in enumerate(['one', 'two', 'three']): #这种写法更短?
- 装饰器
- decorator as class:?
- Parametrizing decorators:a second level of wrapping has to be used(在正常的无参数装饰器写法外面再包一层...)
- 保留元信息:@functools.wraps(function) 装饰器内部实现wrapped函数时调用
- 用途:
- 参数校验
- 缓存(FP memoize)
- 代理(?似乎用在Web框架中更容易理解一些)
- Context provider:如@synchronized,自动加锁(这不是Java里的用法嘛)
- ?装饰器能不能运行时动态绑定?那样的话是不是不能使用@语法,直接用原始的f=deco(f)?装饰过的函数如果取消装饰?
- Context managers – the with statement
- with context_manager as context:
- with A() as a, B() as b: #等价于嵌套写法
- As a class:__enter__ __exit__
- 实现为一个单个的函数:@contextlib.contextmanager
- 被装饰的函数内调用一次yield(之前的为__enter__的逻辑,后面的相当于__exit__)
- 其他的helper:closing(element) supress(*exceptions) redirect_stdout(new_target)
语法最佳实践:class级别以上
- 子类里调用基类的方法:
- Base.f(self)
- super(Base, self).f()
- super().f()
- __mro__ : 基类方法查找的线性化
- Descriptors:__set__ __get__ __delete__
- from OpenGL.GL import shaders
- @lazy_class_attribute ???
- Properties ?
- Slots
- Metaprogramming
- __new__(监控对__init__的调用?)
- Metaclasses(在什么情况下会用到?写Web框架?)
- class ClassWithAMetaclass(metaclass=type): pass
- Some tips on code generation
- Hy(Lisp in Py)?
- exec, eval, and compile
- exec(object, globals, locals)
- eval(expression, globals, locals)
- compile(source, filename, mode)
- tree = ast.parse('def hello_world(): print("hello world!")')
- Falcon's compiled router
选择好的名字
- PEP8?
Writing a Package
- PyPA https://github.com/pypa
- PyPI的Trove classifiers
- PEP 396 (Module Version Numbers)
- 安装依赖:from setuptools import setup
- setup(name='...',
-
install_requires=['falcon', 'requests', 'delorean'] #...
- setup.py develop 或 pip -e
- 默认的setup.py install安装到site-packages目录
- 3.3+:PEP 420 – implicit namespace packages
- 如果不包含__init__.py就是名字空间目录?
- 上传到PyPI
- $ python setup.py sdist bdist_wheel
- $ twine upload dist/*
- Standalone封装:
- Popular tools:PyInstaller、cx_Freeze、py2exe/py2app(那么Sublime是怎么封装的?它用的还是2.6老版本)
- Making decompilation harder(?)
部署代码
- Twelve-Factor App:http://12factor.net/
- Codebase:一个代码库,多个部署
- Dependencies:显式声明和隔离依赖
- Config:存储配置到‘环境’
- Backing services:视为附加的资源
- Build, release, run:严格分离构建和运行(?)
- Processes:作为无状态进程执行
- Port binding:导出服务为端口绑定
- Concurrency:由无状态进程来保证水平扩展(?)
- Disposability:快速启动/优雅退出
- Dev/staging/prod parity
- Logs:日志作为事件流
- Admin processes
- Fabric自动化部署 http://www.fabfile.org/
- PyPI mirroring:https://pypi.python.org/pypi/bandersnatch
- devpi:http://doc.devpi.net/
- Using reverse HTTP proxies
- p210 让TLS/HTTPS由Apache/NginX老考虑,Python仅处理http???
- Graceful reloads?
- Gunicorn/uWSGI:kill -HUP
- Code instrumentation and monitoring
- Logging errors – sentry/raven
- Monitoring system and application metrics
- Munin:http://munin-monitoring.org (Master/Worker架构,层次化的存储/聚集/转发?)
- StatsD:https://github.com/etsy/statsd (不提供图表报告,需要另外开发)
- Graphite?
- 应用日志处理
- logrotate(忘记Supervisor/Circus的?)
- Logstash:解析日志,结构化处理(JSON?)并传递到后端(Elasticsearch)+ Kibana(监控/分析/可视化)
- 备选:Fluentd
用其他语言写Python扩展
- Pure C extensions(*)
- 本质上就是注册一个C函数指针的过程。。。
- 释放GIL:Py_BEGIN_ALLOW_THREADS
- 引用计数:
- Passing of ownership
- Borrowed references
- Stolen references
- Cython
- .py ==> .pyx + 类型标记
- with nogil:
- cdef long long fibonacci_cc(unsigned int n) nogil:
- ctypes/cffi:略
管理代码
- Matrix testing:https://tox.readthedocs.org/
项目文档
- 怎么又来reST了,python社区赶快拥抱Markown吧
TDD
- Preventing software regression(似乎有点道理~)
- DDD(文档驱动的测试?)
优化:一般原则和性能分析技术
- Macro-profiling
- profile
- cProfile
- $ python3 -m cProfile myapp.py
- $ gprof2dot.py -f pstats myapp.stats | dot -Tpng -o output.png
- Micro-profiling(局部打桩)
- cProfile API*
- $ python3 -m timeit -s 'a = [str(i) for i in range(10000)]' 's="".join(a)'
- Measuring Pystones
- Profiling memory usage
- Memprof http://jmdana.github.io/memprof/
- memory_profiler
- Pympler http://pythonhosted.org/Pympler/
- objgraph?http://mg.pov.lt/objgraph/
- C code memory leaks
- Valgrind
优化:一些强大的技术
- Reducing the complexity
- Using architectural trade-offs
- 启发式/近似算法
- 推迟工作到任务队列
- 概率数据结构 HyperLogLog
- Caching
并发
- Multithreading
- GIL(当线程访问Python对象时)
- output代理给主线程(否则输出不同步?)
- Multiprocessing
- child_pid = os.fork()
- if child_pid == 0:
-
pid_list.append(
os.getpid())
- from multiprocessing import Process
- Process(target=work, args=(number,)).start() => p.join()
- Using process pools
- with Pool(POOL_SIZE) as pool: results = pool.map(fetch_place, PLACES)
- Using multiprocessing.dummy as a multithreading interface
- from multiprocessing.dummy import Pool as ThreadPool
- 异步编程
- loop.run_until_complete接受的不是普通的函数对象,而是coroutine,而后者是由普通的函数调用语法返回的
- import aiohttp
- session = aiohttp.ClientSession()
- async with session.get('https://maps.googleapis.com/maps/api/geocode/json', params=params) as response:
- result = await response.json() #构造response对象时底层由触发网络IO数据发送吗?
- Integrating nonasynchronous code with async using futures
- from concurrent.futures import Executor, Future
- submit(fn, *args, **kwargs) #<== 返回一个Future对象
- map(func, *iterables, timeout=None, chunksize=1)
- shutdown(wait=True)
- async def fetch_place(place):
- coro = loop.run_in_executor(None, api.geocode, place)
- result = await coro
- return result[0] #不如完全用coroutine改写的程序
有用的设计模式
略
推荐阅读
-
本文介绍了Linux Shell中括号和整数扩展的使用方法,包括命令组、命令替换、初始化数组以及算术表达式和逻辑判断的相关内容。括号中的命令将会在新开的子shell中顺序执行,括号中的变量不能被脚本余下的部分使用。命令替换可以用于将命令的标准输出作为另一个命令的输入。括号中的运算符和表达式符合C语言运算规则,可以用在整数扩展中进行算术计算和逻辑判断。 ...
[详细]
蜡笔小新 2023-12-12 20:48:58
-
本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ...
[详细]
蜡笔小新 2023-12-12 20:02:41
-
-
前言无论使用哪种语言,我们都需要关注性能优化,提高执行效率。选择脚本语言需要持久的速度。在某种程度上,这句话说明了Python作为一种脚 ...
[详细]
蜡笔小新 2023-10-12 16:48:12
-
sh说明:本pandas非卧龙的pandas,而是Python众多科学计算包中的pandas。本次Pandas的简洁介绍,针对的是此包的新手 ...
[详细]
蜡笔小新 2023-10-12 04:03:59
-
申明下哈本篇文章不是自己写的根据网上的文章再加上自己的加加点点反正大部分都是网站的智慧哈!!!1、线程基本概念1.1线程是什么 ...
[详细]
蜡笔小新 2023-10-11 20:55:11
-
我试图提出一些自定义大纲,以达到一些Web可访问性建议.但我不能用Firefox制作.这就是它在Chrome上的外观:而那个图标实际上是一个锚点.在Firefox上,它只概述了整个 ...
[详细]
蜡笔小新 2023-12-14 10:20:38
-
本文介绍了计算机网络的定义和通信流程,包括客户端编译文件、二进制转换、三层路由设备等。同时,还介绍了计算机网络中常用的关键词,如MAC地址和IP地址。 ...
[详细]
蜡笔小新 2023-12-13 16:50:29
-
本文介绍了包的基础知识,包是一种模块,本质上是一个文件夹,与普通文件夹的区别在于包含一个init文件。包的作用是从文件夹级别组织代码,提高代码的维护性。当代码抽取到模块中后,如果模块较多,结构仍然混乱,可以使用包来组织代码。创建包的方法是右键新建Python包,使用方式与模块一样,使用import来导入包。init文件的使用是将文件夹变成一个模块的方法,通过执行init文件来导入包。一个包中通常包含多个模块。 ...
[详细]
蜡笔小新 2023-12-12 17:52:19
-
代码如下在这里插入代码片from__future__importprint_functionimportnumpyasnpfromkeras.preprocessingimpo ...
[详细]
蜡笔小新 2023-10-17 12:30:42
-
Python多线程popen应用场景:有多台设备需要维护,周期短,重复度高;单台设备配备多个IP,需要经常确认网络是否通常;等等其他需要确 ...
[详细]
蜡笔小新 2023-10-16 12:16:56
-
关于Dart,下面两个资源在Dart开发者和专家之间非常流行:Dart语言之旅浏览Dart的所有主要语言特征。灵活的Dart一组指南,向你 ...
[详细]
蜡笔小新 2023-10-16 10:01:41
-
ThreadPoolExecutor核心工作详解ThreadPoolExecutor内部是如何工作的?什么是future对象?线程什么时候被创建 ...
[详细]
蜡笔小新 2023-10-13 13:35:18
-
本文目录一览:1、如何使用python利用api获取天气预报 ...
[详细]
蜡笔小新 2023-10-13 12:11:33
-
篇首语:本文由编程笔记#小编为大家整理,主要介绍了超全的《Django入门教程》上线了,居然还免费!相关的知识,希望对你有一定的参考价值。 ...
[详细]
蜡笔小新 2023-10-12 19:22:19
-
函数的参数作为引用Python唯一支持的参数传递模式是共享传参(callbysharing)。共享传参指函数的各个形参获得实参中各个引用的副本。也就是 ...
[详细]
蜡笔小新 2023-10-12 15:49:35
-