Python编程语言中有哪些鲜为人知但很有用的特性?

尽量将答案限制在Python核心。 每个回答一个特征。 给出一个例子和功能的简短描述,而不仅仅是文档链接。 使用标题作为第一行标记该特性。

快速链接到答案:

参数解包 牙套 链接比较运算符 修饰符 可变默认参数的陷阱/危险 描述符 字典默认的.get值 所以测试 省略切片语法 枚举 其他/ 函数作为iter()参数 生成器表达式 导入该 就地值交换 步进列表 __missing__物品 多行正则表达式 命名字符串格式化 嵌套的列表/生成器推导 运行时的新类型 .pth文件 ROT13编码 正则表达式调试 发送到发电机 交互式解释器中的制表符补全 三元表达式 试着/ / else除外 拆包+打印()函数 与声明


当前回答

>>> from functools import partial
>>> bound_func = partial(range, 0, 10)
>>> bound_func()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> bound_func(2)
[0, 2, 4, 6, 8]

不是真正的隐藏特性,但是partial对于函数的后期计算非常有用。

你可以在初始调用中绑定尽可能多的或尽可能少的参数到你想要的partial,并在以后使用任何剩余的参数调用它(在这个例子中,我已经将begin/end参数绑定到range,但第二次使用step arg调用它)

请参见文档。

其他回答

这不是一个隐藏的功能,但仍然很好:

import os.path as op

root_dir = op.abspath(op.join(op.dirname(__file__), ".."))

保存大量字符时,操作路径!

元组拆包:

>>> (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)

布尔上下文中的对象

空元组、列表、字典、字符串和许多其他对象在布尔上下文中等价于False(非空对象等价于True)。

empty_tuple = ()
empty_list = []
empty_dict = {}
empty_string = ''
empty_set = set()
if empty_tuple or empty_list or empty_dict or empty_string or empty_set:
  print 'Never happens!'

这允许逻辑运算返回它的一个操作数,而不是True/False,这在某些情况下很有用:

s = t or "Default value" # s will be assigned "Default value"
                         # if t is false/empty/none

下划线,它包含解释器显示的最新输出值(在交互式会话中):

>>> (a for a in xrange(10000))
<generator object at 0x81a8fcc>
>>> b = 'blah'
>>> _
<generator object at 0x81a8fcc>

一个方便的web浏览器控制器:

>>> import webbrowser
>>> webbrowser.open_new_tab('http://www.stackoverflow.com')

内置的http服务器。提供当前目录下的文件:

python -m SimpleHTTPServer 8000

在退出

>>> import atexit

Python的禅宗

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!