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

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

快速链接到答案:

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


当前回答

上下文管理器和“with”语句

在PEP 343中引入的上下文管理器是作为一组语句的运行时上下文的对象。

由于该特性使用了新的关键字,它是逐渐引入的:在Python 2.5中通过__future__指令可用。Python 2.6及以上版本(包括Python 3)默认情况下可用。

我经常使用“with”语句,因为我认为这是一个非常有用的结构,下面是一个快速演示:

from __future__ import with_statement

with open('foo.txt', 'w') as f:
    f.write('hello!')

这里在幕后发生的事情是,“with”语句在文件对象上调用特殊的__enter__和__exit__方法。如果with语句体引发任何异常,异常细节也会传递给__exit__,允许在那里进行异常处理。

在这种特殊情况下,这为您做的是,当执行超出with套件的范围时,它保证关闭文件,无论这是正常发生还是抛出异常。它基本上是一种抽象出常见异常处理代码的方法。

其他常见的用例包括线程锁定和数据库事务。

其他回答

除了haridsv之前提到的这一点之外:

>>> foo = bar = baz = 1
>>> foo, bar, baz
(1, 1, 1)

也可以这样做:

>>> foo, bar, baz = 1, 2, 3
>>> foo, bar, baz
(1, 2, 3)

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

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

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

每次打印一屏多行字符串

没有真正有用的功能隐藏在网站。_Printer类,其license对象是一个实例。调用后者时,打印Python许可证。可以创建另一个相同类型的对象,传递一个字符串——例如文件的内容——作为第二个参数,并调用它:

type(license)(0,open('textfile.txt').read(),0)()

这将打印一次按一定行数分割的文件内容:

...
file row 21
file row 22
file row 23

Hit Return for more, or q (and Return) to quit:

模块导出命名空间中的EVERYTHING

包括从其他模块导入的名称!

# this is "answer42.py"
from operator import *
from inspect  import *

现在测试模块中可导入的内容。

>>> import answer42
>>> answer42.__dict__.keys()
['gt', 'imul', 'ge', 'setslice', 'ArgInfo', 'getfile', 'isCallable', 'getsourcelines', 'CO_OPTIMIZED', 'le', 're', 'isgenerator', 'ArgSpec', 'imp', 'lt', 'delslice', 'BlockFinder', 'getargspec', 'currentframe', 'CO_NOFREE', 'namedtuple', 'rshift', 'string', 'getframeinfo', '__file__', 'strseq', 'iconcat', 'getmro', 'mod', 'getcallargs', 'isub', 'getouterframes', 'isdatadescriptor', 'modulesbyfile', 'setitem', 'truth', 'Attribute', 'div', 'CO_NESTED', 'ixor', 'getargvalues', 'ismemberdescriptor', 'getsource', 'isMappingType', 'eq', 'index', 'xor', 'sub', 'getcomments', 'neg', 'getslice', 'isframe', '__builtins__', 'abs', 'getmembers', 'mul', 'getclasstree', 'irepeat', 'is_', 'getitem', 'indexOf', 'Traceback', 'findsource', 'ModuleInfo', 'ipow', 'TPFLAGS_IS_ABSTRACT', 'or_', 'joinseq', 'is_not', 'itruediv', 'getsourcefile', 'dis', 'os', 'iand', 'countOf', 'getinnerframes', 'pow', 'pos', 'and_', 'lshift', '__name__', 'sequenceIncludes', 'isabstract', 'isbuiltin', 'invert', 'contains', 'add', 'isSequenceType', 'irshift', 'types', 'tokenize', 'isfunction', 'not_', 'istraceback', 'getmoduleinfo', 'isgeneratorfunction', 'getargs', 'CO_GENERATOR', 'cleandoc', 'classify_class_attrs', 'EndOfBlock', 'walktree', '__doc__', 'getmodule', 'isNumberType', 'ilshift', 'ismethod', 'ifloordiv', 'formatargvalues', 'indentsize', 'getmodulename', 'inv', 'Arguments', 'iscode', 'CO_NEWLOCALS', 'formatargspec', 'iadd', 'getlineno', 'imod', 'CO_VARKEYWORDS', 'ne', 'idiv', '__package__', 'CO_VARARGS', 'attrgetter', 'methodcaller', 'truediv', 'repeat', 'trace', 'isclass', 'ior', 'ismethoddescriptor', 'sys', 'isroutine', 'delitem', 'stack', 'concat', 'getdoc', 'getabsfile', 'ismodule', 'linecache', 'floordiv', 'isgetsetdescriptor', 'itemgetter', 'getblock']
>>> from answer42 import getmembers
>>> getmembers
<function getmembers at 0xb74b2924>
>>> 

这是一个不从x import *并定义__all__ =的好理由。

用sum()扁平化列表。

sum()内置函数可用于将__add__个列表放在一起,提供了一种方便的方法来将列表的列表扁平化:

Python 2.7.1 (r271:86832, May 27 2011, 21:41:45) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [[1, 2, 3], [4, 5], [6], [7, 8, 9]]
>>> sum(l, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]