Expert Python Programming, 2nd Edition(读书笔记,似乎对Python 3.5并未着墨强调,但是代码示例容易看懂一点)

本书《Expert Python Programming, 2nd Edition》涵盖了Python 3的最新语法,如print函数、上下文管理器和并发编程。讨论了Python的最佳实践,包括选择好名字、编写包、部署代码和使用TDD。还深入介绍了元编程、优化技术,如使用Cython进行Python扩展,并探讨了用其他语言写Python扩展和并发模型,如多线程、多进程及异步编程。" 50199841,5548851,RecyclerView实现交错网格布局,"['Android开发', '前端框架', '布局管理']
部署运行你感兴趣的模型镜像

Expert Python Programming, 2nd Edition

目录

Python当前状态

  1. Python 3 Wall of Superpowers https://python3wos.appspot.com
  2. Python 3主要语法修改:
    1. print:语句 => 函数
    2. 异常:except ex, e => except ex as e
    3. <>不相等比较 => !=
    4. 不允许在函数中执行from module import *(降低了动态性?)
    5. sort()不接受cmp参数,只允许指定key(见鬼,不支持纯FP风格?)
    6. 浮点数模运算:5.0//2.0 == 2.0
  3. from __future__ import <feature>
  4. PyPy:Python in Python,可以在运行时改变解释器的行为
  5. 3.4+:$ python -m ensurepip
  6. 环境隔离(依赖包的污染问题):virtualenv(依赖于文件系统)、venv、buildout
    1. 3.3+:pyvenv ENV
    2. buildout:自启动+部署
  7. vagrant
  8. Containerization versus virtualization
  9. Custom Python shells – IPython, bpython, ptpython, and so on

语法最佳实践:class级别以下

  1. CPython里的list实际上是用变长数组实现的
  2. for i, element in enumerate(['one', 'two', 'three']): #这种写法更短?
  3. 装饰器
    1. decorator as class:?
    2. Parametrizing decorators:a second level of wrapping has to be used(在正常的无参数装饰器写法外面再包一层...)
    3. 保留元信息:@functools.wraps(function) 装饰器内部实现wrapped函数时调用
    4. 用途:
      1. 参数校验
      2. 缓存(FP memoize)
      3. 代理(?似乎用在Web框架中更容易理解一些)
      4. Context provider:如@synchronized,自动加锁(这不是Java里的用法嘛)
    5. ?装饰器能不能运行时动态绑定?那样的话是不是不能使用@语法,直接用原始的f=deco(f)?装饰过的函数如果取消装饰?
  4. Context managers – the with statement
    1. with context_manager as context:
    2. with A() as a, B() as b: #等价于嵌套写法
    3. As a class:__enter__ __exit__
    4. 实现为一个单个的函数:@contextlib.contextmanager
      1. 被装饰的函数内调用一次yield(之前的为__enter__的逻辑,后面的相当于__exit__)
      2. 其他的helper:closing(element) supress(*exceptions) redirect_stdout(new_target)

语法最佳实践:class级别以上

  1. 子类里调用基类的方法:
    1. Base.f(self)
    2. super(Base, self).f()
    3. super().f()
  2. __mro__ : 基类方法查找的线性化
  3. Descriptors:__set__ __get__ __delete__
    1. from OpenGL.GL import shaders
    2. @lazy_class_attribute ???
  4. Properties ?
  5. Slots
  6. Metaprogramming
    1. __new__(监控对__init__的调用?)
    2. Metaclasses(在什么情况下会用到?写Web框架?)
      1. class ClassWithAMetaclass(metaclass=type): pass
  7. Some tips on code generation
    1. Hy(Lisp in Py)?
    2. exec, eval, and compile
      1. exec(object, globals, locals)
      2. eval(expression, globals, locals)
      3. compile(source, filename, mode)
    3. tree = ast.parse('def hello_world(): print("hello world!")')
    4. Falcon's compiled router

选择好的名字

  1. PEP8?

Writing a Package

  1. PyPA https://github.com/pypa
    1. PyPI的Trove classifiers
      1. PEP 396 (Module Version Numbers)
  2. 安装依赖:from setuptools import setup
    1. setup(name='...',
      install_requires=['falcon', 'requests', 'delorean'] #...
  3. setup.py develop 或 pip -e
    1. 默认的setup.py install安装到site-packages目录
  4. 3.3+:PEP 420 – implicit namespace packages
    1. 如果不包含__init__.py就是名字空间目录?
  5. 上传到PyPI
    1. $ python setup.py sdist bdist_wheel
    2. $ twine upload dist/*
  6. Standalone封装:
    1. Popular tools:PyInstaller、cx_Freeze、py2exe/py2app(那么Sublime是怎么封装的?它用的还是2.6老版本)
    2. Making decompilation harder(?)

部署代码

  1. Twelve-Factor App:http://12factor.net/
    1. Codebase:一个代码库,多个部署
    2. Dependencies:显式声明和隔离依赖
    3. Config:存储配置到‘环境’
    4. Backing services:视为附加的资源
    5. Build, release, run:严格分离构建和运行(?)
    6. Processes:作为无状态进程执行
    7. Port binding:导出服务为端口绑定
    8. Concurrency:由无状态进程来保证水平扩展(?)
    9. Disposability:快速启动/优雅退出
    10. Dev/staging/prod parity
    11. Logs:日志作为事件流
    12. Admin processes
  2. Fabric自动化部署 http://www.fabfile.org/
  3. PyPI mirroring:https://pypi.python.org/pypi/bandersnatch
    1. devpi:http://doc.devpi.net/
  4. Using reverse HTTP proxies
    1. p210 让TLS/HTTPS由Apache/NginX老考虑,Python仅处理http???
  5. Graceful reloads?
    1. Gunicorn/uWSGI:kill -HUP <gunicorn-master-process-pid>
  6. Code instrumentation and monitoring
  7. Logging errors – sentry/raven
  8. Monitoring system and application metrics
    1. Munin:http://munin-monitoring.org (Master/Worker架构,层次化的存储/聚集/转发?)
    2. StatsD:https://github.com/etsy/statsd (不提供图表报告,需要另外开发)
      1. Graphite?
  9. 应用日志处理
    1. logrotate(忘记Supervisor/Circus的?)
    2. Logstash:解析日志,结构化处理(JSON?)并传递到后端(Elasticsearch)+ Kibana(监控/分析/可视化)
      1. 备选:Fluentd

用其他语言写Python扩展

  1. Pure C extensions(*)
    1. 本质上就是注册一个C函数指针的过程。。。
    2. 释放GIL:Py_BEGIN_ALLOW_THREADS
    3. 引用计数:
      1. Passing of ownership
      2. Borrowed references
      3. Stolen references
  2. Cython
    1. .py ==> .pyx + 类型标记
    2. with nogil:
      1. cdef long long fibonacci_cc(unsigned int n) nogil:
  3. ctypes/cffi:略

管理代码

  1. Matrix testing:https://tox.readthedocs.org/

项目文档

  1. 怎么又来reST了,python社区赶快拥抱Markown吧

TDD

  1. Preventing software regression(似乎有点道理~)
  2. DDD(文档驱动的测试?)

优化:一般原则和性能分析技术

  1. Macro-profiling
    1. profile
    2. cProfile
      1. $ python3 -m cProfile myapp.py
      2. $ gprof2dot.py -f pstats myapp.stats | dot -Tpng -o output.png
  2. Micro-profiling(局部打桩)
    1. cProfile API*
    2. $ python3 -m timeit -s 'a = [str(i) for i in range(10000)]' 's="".join(a)'
  3. Measuring Pystones
  4. Profiling memory usage
    1. Memprof http://jmdana.github.io/memprof/
    2. memory_profiler
    3. Pympler http://pythonhosted.org/Pympler/
    4. objgraph?http://mg.pov.lt/objgraph/
  5. C code memory leaks
    1. Valgrind

优化:一些强大的技术

  1. Reducing the complexity
  2. Using architectural trade-offs
    1. 启发式/近似算法
    2. 推迟工作到任务队列
    3. 概率数据结构 HyperLogLog
  3. Caching

并发

  1. Multithreading
    1. GIL(当线程访问Python对象时)
    2. output代理给主线程(否则输出不同步?)
  2. Multiprocessing
    1. child_pid = os.fork()
      1. if child_pid == 0:
        pid_list.append( os.getpid())
    2. from multiprocessing import Process
      1. Process(target=work, args=(number,)).start() => p.join()
    3. Using process pools
      1. with Pool(POOL_SIZE) as pool: results = pool.map(fetch_place, PLACES)
    4. Using multiprocessing.dummy as a multithreading interface
      1. from multiprocessing.dummy import Pool as ThreadPool
  3. 异步编程
    1. loop.run_until_complete接受的不是普通的函数对象,而是coroutine,而后者是由普通的函数调用语法返回的
    2. import aiohttp
      1. session = aiohttp.ClientSession()
      2. async with session.get('https://maps.googleapis.com/maps/api/geocode/json', params=params) as response:
        1. result = await response.json() #构造response对象时底层由触发网络IO数据发送吗?
    3. Integrating nonasynchronous code with async using futures
      1. from concurrent.futures import Executor, Future
        1. submit(fn, *args, **kwargs) #<== 返回一个Future对象
        2. map(func, *iterables, timeout=None, chunksize=1)
        3. shutdown(wait=True)
      2. async def fetch_place(place):
        1. coro = loop.run_in_executor(None, api.geocode, place)
        2. result = await coro
        3. return result[0] #不如完全用coroutine改写的程序

有用的设计模式

略 

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值