Expert Python Programming, 2nd Edition
目录
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 <feature>
- 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)
- PyPI的Trove classifiers
- 安装依赖:from setuptools import setup
- setup(name='...',
- install_requires=['falcon', 'requests', 'delorean'] #...
- setup(name='...',
- 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 <gunicorn-master-process-pid>
- 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())
- if child_pid == 0:
- 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
- child_pid = os.fork()
- 异步编程
- 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改写的程序
- from concurrent.futures import Executor, Future
本书《Expert Python Programming, 2nd Edition》涵盖了Python 3的最新语法,如print函数、上下文管理器和并发编程。讨论了Python的最佳实践,包括选择好名字、编写包、部署代码和使用TDD。还深入介绍了元编程、优化技术,如使用Cython进行Python扩展,并探讨了用其他语言写Python扩展和并发模型,如多线程、多进程及异步编程。"
50199841,5548851,RecyclerView实现交错网格布局,"['Android开发', '前端框架', '布局管理']
675

被折叠的 条评论
为什么被折叠?



