def__next__(self): """调用时返回下一个对象""" try: word = self.words[self._index] except IndexError: raise StopIteration() else: self._index += 1 return word
sentence = Sentence('Return a list of all non-overlapping matches in the string.') assert isinstance(sentence, abc.Iterable) # 实现了 __iter__,就支持 Iterable 协议 assert isinstance(iter(sentence), abc.Iterator) for word in sentence: print(word, end='·')
#!/usr/bin/python #**coding:utf-8** import sys from prettytable import PrettyTable from prettytable import MSWORD_FRIENDLY from prettytable import PLAIN_COLUMNS from prettytable import RANDOM from prettytable import DEFAULT
list(map(fact, range(6))) [fact(n) for n in range(6)] list(map(factorial, filter(lambda n : n % 2, range(6)))) [factorial(n) for n in range(6) if n % 2]
map 和 filter 返回生成器,可用生成器表达式替代 reduce 常用求和,目前最好使用 sum 替代
1 2 3 4 5
from functools import reduce from operator import add
Output the contents of the database as a fixture of the given format (using each model's default manager unless --all is specified). positional arguments: app_label[.ModelName] Restricts dumped data to the specified app_label or app_label.ModelName. optional arguments: -h, --help show this help message and exit --format FORMAT Specifies the output serialization format for fixtures. --indent INDENT Specifies the indent level to use when pretty-printing output. --database DATABASE Nominates a specific database to dump fixtures from. Defaults to the "default" database. -e EXCLUDE, --exclude EXCLUDE An app_label or app_label.ModelName to exclude (use multiple --exclude to exclude multiple apps/models). --natural-foreign Use natural foreign keys if they are available. --natural-primary Use natural primary keys if they are available. -a, --all Use Django's base manager to dump all models stored in the database, including those that would otherwise be filtered or modified by a custom manager. --pks PRIMARY_KEYS Only dump objects with given primary keys. Accepts a comma-separated list of keys. This option only works when you specify one model. -o OUTPUT, --output OUTPUT Specifies file to which the output is written. --version show program's version number and exit -v {0,1,2,3}, --verbosity {0,1,2,3} Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output --settings SETTINGS The Python path to a settings module, e.g. "myproject.settings.main". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used. --pythonpath PYTHONPATH A directory to add to the Python path, e.g. "/home/djangoprojects/myproject". --traceback Raise on CommandError exceptions --no-color Don't colorize the command output. --force-color Force colorization of the command output.
""" Docstring reporter.py is used to generate a html report for specific build. """
# Standard library import os import re from collections import namedtuple
# Third party lib # Import multi-subcass from A package. from jinja2 import ( Environment, FileSystemLoader, Template, select_autoescape) from jira import JIRA
# If you have lcoal import # from .utils import X # from . import utils
要优于 try: # Too broad! return handle_value(collection[key]) except KeyError: # Will also catch KeyError raised by handle_value() return key_not_found(key)
使用startswith() and endswith()代替切片进行序列前缀或后缀的检查。比如
1 2 3 4 5
Yes: if foo.startswith(‘bar’):优于 No: if foo[:3] == ‘bar’: - 使用isinstance()比较对象的类型。比如 Yes: if isinstance(obj, int): 优于 No: if type(obj) is type(1):
判断序列空或不空,有如下规则
1 2 3 4 5
Yes: ifnot seq: if seq: 优于 No: if len(seq) ifnot len(seq)
# 比较两段代码 symbols = 'abcde' # 1 codes = [] for symbol in symbols: codes.append(ord(symbol)) print(codes) # 2 codes = [ord(symbol) for symbol in symbols] print(codes)
列表推导能够提升可读性。 只用列表推导来创建新的列表,并尽量保持简短(不要超过一行)
列表推导同 filter 和 map 的比较
1 2 3 4 5 6 7
symbols = 'abcde'
beyond_ascii = [ord(s) for s in symbols if ord(s) > 100] print(beyond_ascii)
beyond_ascii = list(filter(lambda c: c > 100, map(ord, symbols))) print(beyond_ascii)
# 需要两个参数,类名和类各个字段的名字 City = namedtuple('City', 'name country population coordinates') tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 129.691667)) print(tokyo) print(tokyo.population) print(tokyo.coordinates)
RUN apt-get update RUN apt-get upgrade -y RUN apt-get install -y nodejs ssh mysql RUNcd /app && npm install
# this should start three processes, mysql and ssh # in the background and node app in foreground # isn't it beautifully terrible? <3 CMD mysql & sshd & npm start
#!/usr/bin/env sh # $0 is a script name, # $1, $2, $3 etc are passed arguments # $1 is our command CMD=$1
case"$CMD"in "dev" ) npm install export NODE_ENV=development exec npm run dev ;;
"start" ) # we can modify files here, using ENV variables passed in # "docker create" command. It can't be done during build process. echo"db: $DATABASE_ADDRESS" >> /app/config.yml export NODE_ENV=production exec npm start ;;
* ) # Run custom command. Thanks to this line we can still use # "docker run our_image /bin/bash" and it will work exec$CMD${@:2} ;; esac
# env variables required during build ENV PROJECT_DIR=/app
WORKDIR$PROJECT_DIR
COPY package.json $PROJECT_DIR RUN npm install COPY . $PROJECT_DIR
# env variables that can change # volume and port settings # and defaults for our application ENV MEDIA_DIR=/media \ NODE_ENV=production \ APP_PORT=3000