Google Python Style Guide

迭代器与生成器

  1. next() & stopException
  2. enumerate()
  1. >>> my_list = ['a', 'b', 'c']
  2. >>> for idx, val in enumerate(my_list, 1):
  3. ... print(idx, val)
  4. ...
  5. 1 a
  6. 2 b
  7. 3 c
  1. zip()同时迭代多个序列,tuple
  1. >>> a = [1, 2, 3]
  2. >>> b = ['w', 'x', 'y', 'z']
  3. >>> for i in zip(a,b):
  4. ... print(i)
  5. ...
  6. (1, 'w')
  7. (2, 'x')
  8. (3, 'y')
  9. >>> zip(a, b)
  10. <zip object at 0x1007001b8>
  11. >>> list(zip(a, b))
  12. [(1, 10), (2, 11), (3, 12)]
  1. itertools.chain()
  1. >>> from itertools import chain
  2. >>> a = [1, 2, 3, 4]
  3. >>> b = ['x', 'y', 'z']
  4. >>> for x in chain(a, b):
  5. ... print(x)
  6. ...
  7. 1
  8. 2
  9. 3
  10. 4
  11. x
  12. y
  13. z
  1. 创建数据处理管道,节约内存
  1. import os
  2. import fnmatch
  3. import gzip
  4. import bz2
  5. import re
  6. def gen_find(filepat, top):
  7. '''
  8. Find all filenames in a directory tree that match a shell wildcard pattern
  9. '''
  10. for path, dirlist, filelist in os.walk(top):
  11. for name in fnmatch.filter(filelist, filepat):
  12. yield os.path.join(path,name)
  13. def gen_opener(filenames):
  14. '''
  15. Open a sequence of filenames one at a time producing a file object.
  16. The file is closed immediately when proceeding to the next iteration.
  17. '''
  18. for filename in filenames:
  19. if filename.endswith('.gz'):
  20. f = gzip.open(filename, 'rt')
  21. elif filename.endswith('.bz2'):
  22. f = bz2.open(filename, 'rt')
  23. else:
  24. f = open(filename, 'rt')
  25. yield f
  26. f.close()
  27. def gen_concatenate(iterators):
  28. '''
  29. Chain a sequence of iterators together into a single sequence.
  30. '''
  31. for it in iterators:
  32. yield from it
  33. def gen_grep(pattern, lines):
  34. '''
  35. Look for a regex pattern in a sequence of lines
  36. '''
  37. pat = re.compile(pattern)
  38. for line in lines:
  39. if pat.search(line):
  40. yield line
  1. heapq.merge()顺序迭代合并后的排序迭代对象,输入必须是已经排序过的
>>> import heapq
>>> a = [1, 4, 7, 10]
>>> b = [2, 5, 6, 11]
>>> for c in heapq.merge(a, b):
...     print(c)
...
1
2
4
5
6
7
10
11

文件与IO

  1. 文件读写

mode r, rb, w, wb, w+, a+, ab+

encoding utf-8, gbk

  1. 打印输入到文件中
with open('d:/work/test.txt', 'wt') as f:
    print('Hello World!', file=f)
  1. 文件不存在才能写入xt, xb
>>> import os
>>> if not os.path.exists('somefile'):
...     with open('somefile', 'wt') as f:
...         f.write('Hello\n')
... else:
...     print('File already exists!')
...
File already exists!
  1. 读取二进制数据到可变缓冲区中readinto()
  2. os.path()
>>> import os
>>> path = '/Users/beazley/Data/data.csv'

>>> # Get the last component of the path
>>> os.path.basename(path)
'data.csv'

>>> # Get the directory name
>>> os.path.dirname(path)
'/Users/beazley/Data'

>>> # Join path components together
>>> os.path.join('tmp', 'data', os.path.basename(path))
'tmp/data/data.csv'

>>> # Expand the user's home directory
>>> path = '~/Data/data.csv'
>>> os.path.expanduser(path)
'/Users/beazley/Data/data.csv'

>>> # Split the file extension
>>> os.path.splitext(path)
('~/Data/data', '.csv')

>>> os.path.exists('/etc/passwd')
True # File exists
>>> os.path.exists('/tmp/spam')
False # File does not exists

>>> # Is a regular file
>>> os.path.isfile('/etc/passwd')
True

>>> # Is a directory
>>> os.path.isdir('/etc/passwd')
False

>>> # Is a symbolic link
>>> os.path.islink('/usr/local/bin/python3')
True

>>> # Get the file linked to
>>> os.path.realpath('/usr/local/bin/python3')
'/usr/local/bin/python3.3'
  1. 文件列表匹配 os.listdir(),glob, fnmatch

os.walk

import os
def file_name(file_dir):
    for root, dirs, files in os.walk(file_dir):
        print('root_dir:', root)  # 当前目录路径
        print('sub_dirs:', dirs)  # 当前路径下所有子目录
        print('files:', files)  # 当前路径下所有非目录子文件

glob.glob

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']


  1. 与串行端口的数据通信serial
import serial
ser = serial.Serial('/dev/tty.usbmodem641', # Device name varies
                    baudrate=9600,
                    bytesize=8,
                    parity='N',
                    stopbits=1)

数据编码与处理

  1. csv文件

csv.reader(),pandas.read_csv()

  1. json数据
# Writing JSON data
with open('data.json', 'w') as f:
    json.dump(data, f)

# Reading data back
with open('data.json', 'r') as f:
    data = json.load(f)

# print json data pretty
pprint(data)
  1. xml数据xml.etree.ElementTree
from urllib.request import urlopen
from xml.etree.ElementTree import parse

# Download the RSS feed and parse it
u = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)

# Extract and output tags of interest
for item in doc.iterfind('channel/item'):
    title = item.findtext('title')
    date = item.findtext('pubDate')
    link = item.findtext('link')

    print(title)
    print(date)
    print(link)
    print()

>>> doc
<xml.etree.ElementTree.ElementTree object at 0x101339510>
>>> e = doc.find('channel/title')
>>> e
<Element 'title' at 0x10135b310>
>>> e.tag
'title'
>>> e.text
'Planet Python'
>>> e.get('some_attribute')
  1. 字典转换为xml
from xml.etree.ElementTree import Element

def dict_to_xml(tag, d):
'''
Turn a simple dict of key/value pairs into XML
'''
elem = Element(tag)
for key, val in d.items():
    child = Element(key)
    child.text = str(val)
    elem.append(child)
return elem
  1. 修改xml文件
>>> from xml.etree.ElementTree import parse, Element
>>> doc = parse('pred.xml')
>>> root = doc.getroot()
>>> root
<Element 'stop' at 0x100770cb0>

>>> # Remove a few elements
>>> root.remove(root.find('sri'))
>>> root.remove(root.find('cr'))
>>> # Insert a new element after <nm>...</nm>
>>> root.getchildren().index(root.find('nm'))
1
>>> e = Element('spam')
>>> e.text = 'This is a test'
>>> root.insert(2, e)

>>> # Write back to a file
>>> doc.write('newpred.xml', xml_declaration=True)
  1. 与关系型数据库的交互
>>> import sqlite3
>>> db = sqlite3.connect('database.db')
>>> c = db.cursor()
>>> c.execute('create table portfolio (symbol text, shares integer, price real)')
<sqlite3.Cursor object at 0x10067a730>
>>> db.commit()
>>> c.executemany('insert into portfolio values (?,?,?)', stocks)
<sqlite3.Cursor object at 0x10067a730>
>>> db.commit()
>>> for row in db.execute('select * from portfolio'):
...     print(row)
>>> #用户输入参数
>>> min_price = 100
>>> for row in db.execute('select * from portfolio where price >= ?',
                          (min_price,)):
...     print(row)
  1. 数据的统计操作 Pandas

Numpy is faster

函数

  1. 可接受任意数量参数的函数
def avg(first, *rest):
    return (first + sum(rest)) / (1 + len(rest))

# Sample use
avg(1, 2) # 1.5
avg(1, 2, 3, 4) # 2.5
  1. 回调函数callback()

类与对象

  1. 创建可管理的属性
import math
class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):
        return math.pi * self.radius ** 2

    @property
    def diameter(self):
        return self.radius * 2

    @property
    def perimeter(self):
        return 2 * math.pi * self.radius

>>> c = Circle(4.0)
>>> c.radius
4.0
>>> c.area  # Notice lack of ()
50.26548245743669
>>> c.perimeter  # Notice lack of ()
25.132741228718345

元编程

Don’t repeat yourself. 元编程就是关于创建操作源代码(比如修改、生成或包装原来的代码)的函数和类。 主要技术是使用装饰器、类装饰器和元类

  1. 在函数上添加装饰器,增加额外的操作处理(比如日志、计时等)
import time
from functools import wraps

def timethis(func):
    '''
    Decorator that reports the execution time.
    '''
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(func.__name__, end-start)
        return result
    return wrapper

>>> @timethis
... def countdown(n):
...     '''
...     Counts down
...     '''
...     while n > 0:
...         n -= 1
...
>>> countdown(100000)
countdown 0.008917808532714844
>>> countdown(10000000)
countdown 0.87188299392912
  1. 定义一个带参数的装饰器
from functools import wraps
import logging

def logged(level, name=None, message=None):
    """
    Add logging to a function. level is the logging
    level, name is the logger name, and message is the
    log message. If name and message aren't specified,
    they default to the function's module and name.
    """
    def decorate(func):
        logname = name if name else func.__module__
        log = logging.getLogger(logname)
        logmsg = message if message else func.__name__

        @wraps(func)
        def wrapper(*args, **kwargs):
            log.log(level, logmsg)
            return func(*args, **kwargs)
        return wrapper
    return decorate

# Example use
@logged(logging.DEBUG)
def add(x, y):
    return x + y

@logged(logging.CRITICAL, 'example')
def spam():
    print('Spam!')

模块与包

  1. 读取位于包中的数据文件
mypackage/
    __init__.py
    somedata.dat
    spam.py

# spam.py
import pkgutil
data = pkgutil.get_data(__package__, 'somedata.dat')
  1. 分发包

典型的目录结构

projectname/
    README.txt
    Doc/
        documentation.txt
    projectname/
        __init__.py
        foo.py
        bar.py
        utils/
            __init__.py
            spam.py
            grok.py
    examples/
        helloworld.py
        ...

要让你的包可以发布出去,首先你要编写一个 setup.py

# setup.py
from distutils.core import setup

setup(name='projectname',
    version='1.0',
    author='Your Name',
    author_email='you@youraddress.com',
    url='http://www.you.com/projectname',
    packages=['projectname', 'projectname.utils'],
)

下一步,就是创建一个 MANIFEST.in
文件,列出所有在你的包中需要包含进来的非源码文件:

# MANIFEST.in
include *.txt
recursive-include examples *
recursive-include Doc *

确保 setup.py 和 MANIFEST.in 文件放在你的包的最顶级目录中。 一旦你已经做了这些,你就可以像下面这样执行命令来创建一个源码分发包了:

python3 setup.py sdist

网络与web编程

  1. 作为客户端与HTTP服务交互

简单的urllib.request, 复杂一点的request库

  1. 创建TCP/UDP服务器

socketserver库

  1. 创建一个简单的REST接口
  2. 简单的客户端认证
  3. hmac模块
  4. 发送与接收大型数组
  5. memoryviews

并发编程

多线程类似于同时执行多个不同程序,多线程运行有如下优点:

使用线程可以把占据长时间的程序中的任务放到后台去处理;

用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度;

程序的运行速度可能加快;

在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占用等等。

  1. 启动与停止线程

由于全局解释锁(GIL)的原因,Python 的线程被限制到同一时刻只允许一个线程执行这样一个执行模型。所以,Python 的线程更适用于处理I/O和其他需要并发执行的阻塞操作(比如等待I/O、等待从数据库获取数据等等),而不是需要多处理器并行的计算密集型任务。

# Code to execute in an independent thread
import time
def countdown(n):
    while n > 0:
        print('T-minus', n)
        n -= 1
        time.sleep(5)

# Create and launch a thread
from threading import Thread
t = Thread(target=countdown, args=(10,))
t.start()

Python中的线程会在一个单独的系统级线程中执行(比如说一个 POSIX 线程或者一个 Windows 线程),这些线程将由操作系统来全权管理。线程一旦启动,将独立执行直到目标函数返回。你可以查询一个线程对象的状态,看它是否还在执行:

if t.is_alive():
    print('Still running')
else:
    print('Completed')

Python解释器直到所有线程都终止前仍保持运行。对于需要长时间运行的线程或者需要一直运行的后台任务,你应当考虑使用后台线程。 例如:

t = Thread(target=countdown, args=(10,), daemon=True)
t.start()

如果线程执行一些像I/O这样的阻塞操作,那么通过轮询来终止线程将使得线程之间的协调变得非常棘手。比如,如果一个线程一直阻塞在一个I/O操作上,它就永远无法返回,也就无法检查自己是否已经被结束了。要正确处理这些问题,你需要利用超时循环来小心操作线程。 例子如下:

class IOTask:
    def terminate(self):
        self._running = False

    def run(self, sock):
        # sock is a socket
        sock.settimeout(5)        # Set timeout period
        while self._running:
            # Perform a blocking I/O operation w/ timeout
            try:
                data = sock.recv(8192)
                break
            except socket.timeout:
                continue
            # Continued processing
            ...
        # Terminated
        return
  1. 判断线程是否已经启动