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

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

快速链接到答案:

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


当前回答

...dict.get()有一个默认值None,从而避免KeyErrors:

In [1]: test = { 1 : 'a' }

In [2]: test[2]
---------------------------------------------------------------------------
<type 'exceptions.KeyError'>              Traceback (most recent call last)

&lt;ipython console&gt; in <module>()

<type 'exceptions.KeyError'>: 2

In [3]: test.get( 2 )

In [4]: test.get( 1 )
Out[4]: 'a'

In [5]: test.get( 2 ) == None
Out[5]: True

甚至在“现场”指定这个:

In [6]: test.get( 2, 'Some' ) == 'Some'
Out[6]: True

你可以使用setdefault()来设置一个值,如果它不存在就返回:

>>> a = {}
>>> b = a.setdefault('foo', 'bar')
>>> a
{'foo': 'bar'}
>>> b
'bar

其他回答

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

from __future__ import braces

不是“隐藏”,而是很有用,不常用

像这样快速创建字符串连接函数

 comma_join = ",".join
 semi_join  = ";".join

 print comma_join(["foo","bar","baz"])
 'foo,bar,baz

and

能够更优雅地创建字符串列表,而不是引号,逗号混乱。

l = ["item1", "item2", "item3"]

取而代之的是

l = "item1 item2 item3".split()

获取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)

使用and和or来模拟第三运算符。

python中的and和or操作符返回对象本身,而不是布尔值。因此:

In [18]: a = True

In [19]: a and 3 or 4
Out[19]: 3

In [20]: a = False

In [21]: a and 3 or 4
Out[21]: 4

然而,Py 2.5似乎添加了一个显式的第三运算符

    In [22]: a = 5 if True else '6'

    In [23]: a
    Out[23]: 5

好吧,如果你确定你的true子句的结果不是False,这是可行的。例子:

>>> def foo(): 
...     print "foo"
...     return 0
...
>>> def bar(): 
...     print "bar"
...     return 1
...
>>> 1 and foo() or bar()
foo
bar
1

要做到这一点,你还需要多做一点:

>>> (1 and [foo()] or [bar()])[0]
foo
0

然而,这并不漂亮。如果你的python版本支持它,请使用条件操作符。

>>> foo() if True or bar()
foo
0

分配和删除切片:

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:5] = [42]
>>> a
[42, 5, 6, 7, 8, 9]
>>> a[:1] = range(5)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[::2]
>>> a
[1, 3, 5, 7, 9]
>>> a[::2] = a[::-2]
>>> a
[9, 3, 5, 7, 1]

注意:当赋值给扩展片(s[start:stop:step])时,赋值的可迭代对象必须与片的长度相同。