deftag(name, *content, cls=None, **attrs): """Generate one or more HTML tag""" if cls isnotNone: attrs['class'] = cls if attrs: attr_str = ''.join(' %s="%s"' % (attr, value) for attr, value insorted(attrs.items()))
else: attr_str = '' if content: return'\n'.join('<%s%s>%s</%s>' % (name, attr_str, c, name) for c in content)
defclip(text, max_len=80): """Return text clipped at the last space before or after max_len""" end = None iflen(text) > max_len: space_before = text.rfind(' ', 0, max_len) if space_before >= 0: end = space_before else: space_after = text.rfind(' ', max_len) if space_after >= 0: end = space_after if end isNone: end = len(text) return text[:end].rstrip()
from inspect import signature sig = signature(clip) print(sig) print(str(sig)) for name, param in sig.parameters.items(): print(param.kind, ':', name, '=', param.default)
使用inspect/Signature可以实现类似查看函数元数据的功能
函数注解
Python3能够添加元数据到函数声明的参数和返回值上
1
defclip(text: str, max_len: 'int > 0'=80) -> str:
函数编程的包
operator模块
1 2 3 4 5 6 7 8
from functools import reduce from operator import mul
deffact(n): return reduce(lambda a, b: a * b, range(1, n + 1))
deffact_op(n): return reduce(mul, range(1, n + 1))
1 2 3 4 5 6
from operator import methodcaller s = 'The time has come' upcase = methodcaller('upper') print(upcase(s)) hiphenate = methodcaller('replace', ' ', '-') print(hiphenate(s))