python 3.5 新特性分析

文章来源

https://docs.python.org/3/whatsnew/3.5.html

python3.5 新特性

标准库的重大改进:

collections.OrderedDict 改用C实现,性能快4到100倍。
ssl模块获得了 对 Memory BIO 的支持,它将SSL协议处理与网络IO分离。
os.scandir()函数提供了一种更快速的目录遍历方式。
functools.lru_cache() 中大部分方法在C中重新实现,产生了更好的性能。
subprocess.run()函数提供了一种简化的方法来运行子进程。
traceback模块性能显着增强。

新功能

PEP 492通过添加awaitable objects, coroutine functions, asynchronous iteration, asynchronous context managers,改进了Python中异步编程的支持。
使用新语法声明协程函数:

声明协程函数:async def
异步迭代: async for
异步上下文管理器:async with

注意点:
1、await表达式可用于暂停协程执行,直到结果可用。只要通过定义__await__()方法实现等待协议,就可以等待任何对象。
2、async for 和 async with只能用在async def声明的函数中使用。 

使用新语法编写的基本HTTP客户端示例:

import asyncio

async def http_get(domain):
    reader, writer = await asyncio.open_connection(domain, 80)

    writer.write(b'\r\n'.join([
        b'GET / HTTP/1.1',
        b'Host: %b' % domain.encode('latin-1'),
        b'Connection: close',
        b'', b''
    ]))

    async for line in reader:
        print('>>>', line)

    writer.close()

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(http_get('example.com'))
finally:
    loop.close()

异步上下文管理器举例:

import asyncio

async def coro(name, lock):
    print('coro {}: waiting for lock'.format(name))
    async with lock:
        print('coro {}: holding the lock'.format(name))
        await asyncio.sleep(1)
        print('coro {}: releasing the lock'.format(name))

loop = asyncio.get_event_loop()
lock = asyncio.Lock()
coros = asyncio.gather(coro(1, lock), coro(2, lock))
try:
    loop.run_until_complete(coros)
finally:
    loop.close()
    
    
输出:
coro 2: waiting for lock
coro 2: holding the lock
coro 1: waiting for lock
coro 2: releasing the lock
coro 1: holding the lock
coro 1: releasing the lock
PEP 448 扩展了*和**的拆包使用范围。现在可以在函数调用中使用任意数量的拆包:
>>> print(*[1], *[2], 3, *[4, 5])
1 2 3 4 5

>>> def fn(a, b, c, d):
...     print(a, b, c, d)


>>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
1 2 3 4

类似地,元组,列表,集和字典显示允许多个解包(请参阅表达式列表和字典显示):

>>> *range(4), 4
(0, 1, 2, 3, 4)

>>> [*range(4), 4]
[0, 1, 2, 3, 4]

>>> {*range(4), 4, *(5, 6, 7)}
{0, 1, 2, 3, 4, 5, 6, 7}

>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}
PEP 484 - 类型提示

从Python3.0开始,函数注释语法一直是Python的特性,然而PEP 3107并没有定义注释的语法。
PEP 484引入了provisional module,以提供这些标准定义和工具,以及一些不适用注释的情况的约定。

例如,这是一个简单的函数,其参数和返回类型在注释中声明:

def greeting(name: str) -> str:
    return 'Hello ' + name

在运行时注释实现了__annotations__方法,但是并不会进行类型检查。

PEP 471 - os.scandir()函数 - 更好更快的目录迭代器

os.scandir()返回一个迭代器,而不是返回文件名列表。os.walk()也使用scandir实现。

举例,打印出指定目录path下文件名以‘测试’开头的文件:

for entry in os.scandir(path):
    if not entry.name.startswith('测试') and entry.is_file():
        print(entry.name)
PEP 479:更改生成器内的StopIteration处理

Python 3.4 版本以及之前,当生成器迭代结束时会抛出 StopIteration 异常,可能会引起一些未知的bug, 在3.5 以后该异常会替换为 RuntimeError 异常。

这是一个向后不兼容的更改,必须导入__future__:

>>> from __future__ import generator_stop

>>> def gen():
...     next(iter([]))
...     yield
...
>>> next(gen())
Traceback (most recent call last):
  File "<stdin>", line 2, in gen
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration

如果没有__future__导入,只要在生成器内引发StopIteration异常,就会引发PendingDeprecationWarning。

PEP 485:用于测试近似值的函数

PEP 485 添加了math.isclose()和cmath.isclose(),根据给定的两个值,绝对公差或相对公差来判断确定是否被认为是接近的。绝对公差或相对公差是isclose方法的参数,是给定的两个值之间允许的最大差异:

>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, rel_tol=1e-5)
True
>>> math.isclose(a, b, rel_tol=1e-6)
False

也可以使用绝对公差来比较两个值,绝对容差必须是非负值:
>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, abs_tol=0.00003)
True
>>> math.isclose(a, b, abs_tol=0.00001)
False

不推荐内容

  1. async 和 await 将成为Python 3.7中的关键字。
  2. CPython 3.5不支持Microsoft Windows XP 操作系统。
  3. 不推荐使用的Python模块,函数和方法:
  • formatter模块现已逐渐完全弃用,将在Python 3.6中删除。
  • asyncio.async()函数已弃用,新增 asyncio.ensure_future()。
  • 不推荐使用format(format_string, *args, **kwargs)传入format_string的形式格式化字符串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值