Python编程语言中有哪些鲜为人知但很有用的特性?
尽量将答案限制在Python核心。
每个回答一个特征。
给出一个例子和功能的简短描述,而不仅仅是文档链接。
使用标题作为第一行标记该特性。
快速链接到答案:
参数解包
牙套
链接比较运算符
修饰符
可变默认参数的陷阱/危险
描述符
字典默认的.get值
所以测试
省略切片语法
枚举
其他/
函数作为iter()参数
生成器表达式
导入该
就地值交换
步进列表
__missing__物品
多行正则表达式
命名字符串格式化
嵌套的列表/生成器推导
运行时的新类型
.pth文件
ROT13编码
正则表达式调试
发送到发电机
交互式解释器中的制表符补全
三元表达式
试着/ / else除外
拆包+打印()函数
与声明
多行字符串
一种方法是使用反斜杠:
>>> sql = "select * from some_table \
where id > 10"
>>> print sql
select * from some_table where id > 10
另一种是使用三引号:
>>> sql = """select * from some_table
where id > 10"""
>>> print sql
select * from some_table where id > 10
问题是它们不是缩进的(在代码中看起来很差)。如果你试着缩进,它只会打印你输入的空白。
第三种解决方案,也是我最近发现的,就是把字符串分成几行,然后用圆括号括起来:
>>> sql = ("select * from some_table " # <-- no comma, whitespace at end
"where id > 10 "
"order by name")
>>> print sql
select * from some_table where id > 10 order by name
注意行与行之间没有逗号(这不是一个元组),并且必须考虑字符串需要的任何尾随/前导空格。顺便说一下,所有这些都使用占位符(例如“我的名字是%s”% name)。
小心可变默认参数
>>> def foo(x=[]):
... x.append(1)
... print x
...
>>> foo()
[1]
>>> foo()
[1, 1]
>>> foo()
[1, 1, 1]
相反,你应该使用一个表示“not given”的哨兵值,并将其替换为你想要的默认值:
>>> def foo(x=None):
... if x is None:
... x = []
... x.append(1)
... print x
>>> foo()
[1]
>>> foo()
[1]
内置方法或函数不实现描述符协议,这使得不可能做这样的事情:
>>> class C(object):
... id = id
...
>>> C().id()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: id() takes exactly one argument (0 given)
然而,你可以创建一个小的绑定描述符来实现这一点:
>>> from types import MethodType
>>> class bind(object):
... def __init__(self, callable):
... self.callable = callable
... def __get__(self, obj, type=None):
... if obj is None:
... return self
... return MethodType(self.callable, obj, type)
...
>>> class C(object):
... id = bind(id)
...
>>> C().id()
7414064
获取python正则表达式解析树来调试正则表达式。
正则表达式是python的一个伟大特性,但调试它们可能是一件痛苦的事情,而且正则表达式很容易出错。
幸运的是,python可以通过将未记录的、实验性的隐藏标志re.DEBUG(实际上是128)传递给re.compile来打印正则表达式解析树。
>>> re.compile("^\[font(?:=(?P<size>[-+][0-9]{1,2}))?\](.*?)[/font]",
re.DEBUG)
at at_beginning
literal 91
literal 102
literal 111
literal 110
literal 116
max_repeat 0 1
subpattern None
literal 61
subpattern 1
in
literal 45
literal 43
max_repeat 1 2
in
range (48, 57)
literal 93
subpattern 2
min_repeat 0 65535
any None
in
literal 47
literal 102
literal 111
literal 110
literal 116
一旦理解了语法,就可以发现错误。在这里我们可以看到,我忘记转义[/font]中的[]。
当然,你可以将它与任何你想要的标志组合在一起,比如注释正则表达式:
>>> re.compile("""
^ # start of a line
\[font # the font tag
(?:=(?P<size> # optional [font=+size]
[-+][0-9]{1,2} # size specification
))?
\] # end of tag
(.*?) # text between the tags
\[/font\] # end of the tag
""", re.DEBUG|re.VERBOSE|re.DOTALL)