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

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

快速链接到答案:

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


当前回答

Doctest:同时进行文档和单元测试。

从Python文档中提取的示例:

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    If the result is small enough to fit in an int, return an int.
    Else return a long.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0

    Factorials of floats are OK, but the float must be an exact integer:
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result

def _test():
    import doctest
    doctest.testmod()    

if __name__ == "__main__":
    _test()

其他回答

>>> 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调用它)

请参见文档。

重新加载模块可以实现“实时编码”风格。但是类实例不更新。以下是原因,以及如何解决这个问题。记住,所有东西,是的,所有东西都是一个对象。

>>> from a_package import a_module
>>> cls = a_module.SomeClass
>>> obj = cls()
>>> obj.method()
(old method output)

现在更改a_module.py中的方法,并希望更新对象。

>>> reload(a_module)
>>> a_module.SomeClass is cls
False # Because it just got freshly created by reload.
>>> obj.method()
(old method output)

这里有一种更新方法(但考虑使用剪刀运行):

>>> obj.__class__ is cls
True # it's the old class object
>>> obj.__class__ = a_module.SomeClass # pick up the new class
>>> obj.method()
(new method output)

这是“剪刀式运行”,因为对象的内部状态可能与新类所期望的不同。这适用于非常简单的情况,但除此之外,pickle是您的朋友。尽管如此,理解为什么这是有效的仍然是有帮助的。

Dict的构造函数接受关键字参数:

>>> dict(foo=1, bar=2)
{'foo': 1, 'bar': 2}

为了添加更多的python模块(特别是第三方模块),大多数人似乎使用PYTHONPATH环境变量,或者在他们的site-packages目录中添加符号链接或目录。另一种方法是使用*.pth文件。以下是python官方文档的解释:

“这是最方便的修改方式 Python的搜索路径]是添加一个路径 配置文件到一个目录 已经在Python的路径上了, 通常到…/site-packages/ 目录中。路径配置文件 扩展名为。pth,每个 行必须包含一个单独的路径 将被追加到sys.path。(因为 新路径被附加到 sys。路径,模块在添加 目录将不会覆盖标准 模块。这意味着你不能使用这个 安装固定机构 标准模块的版本。)

函数参数解包

可以使用*和**将列表或字典解包为函数参数。

例如:

def draw_point(x, y):
    # do some magic

point_foo = (3, 4)
point_bar = {'y': 3, 'x': 2}

draw_point(*point_foo)
draw_point(**point_bar)

非常有用的快捷方式,因为列表、元组和字典被广泛用作容器。