Python编程语言中有哪些鲜为人知但很有用的特性?
尽量将答案限制在Python核心。
每个回答一个特征。
给出一个例子和功能的简短描述,而不仅仅是文档链接。
使用标题作为第一行标记该特性。
快速链接到答案:
参数解包
牙套
链接比较运算符
修饰符
可变默认参数的陷阱/危险
描述符
字典默认的.get值
所以测试
省略切片语法
枚举
其他/
函数作为iter()参数
生成器表达式
导入该
就地值交换
步进列表
__missing__物品
多行正则表达式
命名字符串格式化
嵌套的列表/生成器推导
运行时的新类型
.pth文件
ROT13编码
正则表达式调试
发送到发电机
交互式解释器中的制表符补全
三元表达式
试着/ / else除外
拆包+打印()函数
与声明
只需少量的工作,线程模块就变得非常容易使用。此装饰器更改函数,使其在自己的线程中运行,返回占位符类实例,而不是常规结果。你可以通过检查placeolder来探测答案。结果或通过调用placeholder.awaitResult()来等待它。
def threadify(function):
"""
exceptionally simple threading decorator. Just:
>>> @threadify
... def longOperation(result):
... time.sleep(3)
... return result
>>> A= longOperation("A has finished")
>>> B= longOperation("B has finished")
A doesn't have a result yet:
>>> print A.result
None
until we wait for it:
>>> print A.awaitResult()
A has finished
we could also wait manually - half a second more should be enough for B:
>>> time.sleep(0.5); print B.result
B has finished
"""
class thr (threading.Thread,object):
def __init__(self, *args, **kwargs):
threading.Thread.__init__ ( self )
self.args, self.kwargs = args, kwargs
self.result = None
self.start()
def awaitResult(self):
self.join()
return self.result
def run(self):
self.result=function(*self.args, **self.kwargs)
return thr
在列表推导式中交错if和for
>>> [(x, y) for x in range(4) if x % 2 == 1 for y in range(4)]
[(1, 0), (1, 1), (1, 2), (1, 3), (3, 0), (3, 1), (3, 2), (3, 3)]
直到我学了哈斯克尔,我才意识到这一点。
获取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)
元组拆包:
>>> (a, (b, c), d) = [(1, 2), (3, 4), (5, 6)]
>>> a
(1, 2)
>>> b
3
>>> c, d
(4, (5, 6))
更模糊的是,你可以在函数参数中做到这一点(在Python 2.x中;Python 3。X将不再允许这样):
>>> def addpoints((x1, y1), (x2, y2)):
... return (x1+x2, y1+y2)
>>> addpoints((5, 0), (3, 5))
(8, 5)
条件赋值
x = 3 if (y == 1) else 2
正如它听起来的那样:“如果y是1,则赋3给x,否则赋2给x”。注意,括号不是必需的,但是为了可读性,我喜欢它们。如果你有更复杂的东西,你也可以把它串起来:
x = 3 if (y == 1) else 2 if (y == -1) else 1
虽然在某种程度上,这有点太过分了。
注意,你可以使用if…任何表达式中的Else。例如:
(func1 if y == 1 else func2)(arg1, arg2)
这里,如果y = 1调用func1,否则调用func2。在这两种情况下,对应的函数将调用参数arg1和arg2。
类似地,以下也成立:
x = (class1 if y == 1 else class2)(arg1, arg2)
其中class1和class2是两个类。