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

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

快速链接到答案:

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


当前回答

命名格式

% -formatting接受字典(也应用%i/%s等验证)。

>>> print "The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42}
The answer is 42.

>>> foo, bar = 'question', 123

>>> print "The %(foo)s is %(bar)i." % locals()
The question is 123.

由于locals()也是一个字典,您可以简单地将其作为字典传递,并从局部变量中获得% -替换。我认为这是不受欢迎的,但简化了事情。

新的样式格式

>>> print("The {foo} is {bar}".format(foo='answer', bar=42))

其他回答

如果你不喜欢使用空格来表示作用域,你可以通过发出以下命令来使用c风格{}:

from __future__ import braces

如果你在你的类上使用描述符,Python完全绕过__dict__键,这使得它成为一个存储这些值的好地方:

>>> class User(object):
...  def _get_username(self):
...   return self.__dict__['username']
...  def _set_username(self, value):
...   print 'username set'
...   self.__dict__['username'] = value
...  username = property(_get_username, _set_username)
...  del _get_username, _set_username
... 
>>> u = User()
>>> u.username = "foo"
username set
>>> u.__dict__
{'username': 'foo'}

这有助于保持dir()干净。

使用不同的起始索引进行枚举

enumerate在这个答案中已经部分涉及了,但最近我发现了enumerate一个更隐藏的特性,我认为值得单独发表,而不仅仅是评论。

从Python 2.6开始,你可以在第二个参数中指定要枚举的起始索引:

>>> l = ["spam", "ham", "eggs"]
>>> list(enumerate(l))
>>> [(0, "spam"), (1, "ham"), (2, "eggs")]
>>> list(enumerate(l, 1))
>>> [(1, "spam"), (2, "ham"), (3, "eggs")]

我发现它非常有用的一个地方是当我枚举对称矩阵的元素时。由于矩阵是对称的,我可以通过只在上三角形上迭代来节省时间,但在这种情况下,我必须在内部for循环中使用不同的起始索引来正确跟踪行和列的索引:

for ri, row in enumerate(matrix):
    for ci, column in enumerate(matrix[ri:], ri):
        # ci now refers to the proper column index

奇怪的是,enumerate的这种行为在help(enumerate)中没有记录,只有在线文档中有记录。

当使用交互式shell时,"_"包含最后一个打印项的值:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> _
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Monkeypatching对象

Python中的每个对象都有__dict__成员,用于存储对象的属性。所以,你可以这样做:

class Foo(object):
    def __init__(self, arg1, arg2, **kwargs):
        #do stuff with arg1 and arg2
        self.__dict__.update(kwargs)

f = Foo('arg1', 'arg2', bar=20, baz=10)
#now f is a Foo object with two extra attributes

可以利用这一点向对象任意添加属性和函数。这也可以用来创建一个快速和肮脏的结构类型。

class struct(object):
    def __init__(**kwargs):
       self.__dict__.update(kwargs)

s = struct(foo=10, bar=11, baz="i'm a string!')