aaa0的个人博客分享 http://blog.sciencenet.cn/u/aaa0

博文

[转载]海象运算符 :=

已有 3758 次阅读 2019-11-26 22:54 |系统分类:科研笔记|文章来源:转载

 

PEP 572: Assignment Expressions

新增一种新语法形式::=,又称为“海象运算符”(为什么叫海象,看看这两个符号像不像颜表情),如果你用过 Go 语言,应该对这个语法非常熟悉。

具体作用我们直接用实例来展示,比如在使用正则匹配时,以往版本中我们会如下写:

import re pattern = re.compile('a') data = 'abc' match = pattern.search(data) if match is not None:     print(match.group(0)) 复制代码

而使用赋值表达式时,我们可以改写为:

if (match := pattern.search(data)) is not None:     print(match.group(0)) 复制代码

在 if 语句中同时完成了求值、赋值变量、变量判断三步操作,再次简化了代码。

下面是在列表表达式中的用法:

filtered_data = [y for x in data if (y := func(x)) is not None] 复制代码

强制位置参数

PEP 570: Python Positional-Only parameters

新增一个函数形参标记:/,用来表示标记左侧的参数,都只接受位置参数,不能使用关键字参数形式。

>>> def pow(x, y, z=None, /): ...     r = x ** y ...     return r if z is None else r%z ... >>> pow(5, 3) 125 >>> pow(x=5, y=3) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: pow() takes no keyword arguments 复制代码

这实际上是用纯 Python 代码来模拟现有 C 代码实现的内置函数中类似功能,比如内置函数 len('string') 传参是不能使用关键字参数的。

Runtime 审计钩子

PEP 578: Python Runtime Audit Hooks

这让我们可以对某些事件和 API 添加一些钩子,用于在运行时监听事件相关的参数。

比如这里监听 urllib 请求:

>>> import sys >>> import urllib.request >>> def audit_hook(event, args): ...     if event in ['urllib.Request']: ...         print(f'{event=} {args=}') ... >>> sys.addaudithook(audit_hook) >>> urllib.request.urlopen('https://httpbin.org/get?a=1') event = 'urllib.Request' args =( 'https://httpbin.org/get?a=1' , None , {}, 'GET' ) <http.client.HTTPResponse object at 0x108f09b38> 复制代码

官方内置了一些 API,具体可查看 PEP-578 规范文档,也可以自定义。

f-strings 支持等号

在 Python 3.6 版本中增加了 f-strings,可以使用 f 前缀更方便地格式化字符串,同时还能进行计算,比如:

>>> x = 10 >>> print(f'{x+1}') 11 复制代码

在 3.8 中只需要增加一个 = 符号,即可拼接运算表达式与结果:

>>> x = 10 >>> print(f'{x+1=}') 'x+1=11' 复制代码

这个特性官方指明了适用于 Debug。

Asyncio 异步交互模式

在之前版本的 Python 交互模式中(REPL),涉及到 Asyncio 异步函数,通常需要使用 asyncio.run(func()) 才能执行。

而在 3.8 版本中,当使用 python -m asyncio 进入交互模式,则不再需要 asyncio.run

>>> import asyncio >>> async def test(): ...     await asyncio.sleep(1) ...     return 'test' ... >>> await test() 'test' 复制代码

跨进程共享内存

在 Python 多进程中,不同进程之间的通信是常见的问题,通常的方式是使用 multiprocessing.Queue 或者 multiprocessing.Pipe,在 3.8 版本中加入了 multiprocessing.shared_memory,利用专用于共享 Python 基础对象的内存区域,为进程通信提供一个新的选择。

from multiprocessing import Process from multiprocessing import shared_memory share_nums = shared_memory.ShareableList(range(5)) def work1(nums):     for i in range(5):         nums[i] += 10     print('work1 nums = %s'% nums) def work2(nums):     print('work2 nums = %s'% nums) if __name__ == '__main__':     p1 = Process(target=work1, args=(share_nums, ))     p1.start()     p1.join()     p2 = Process(target=work2, args=(share_nums, ))     p2.start() # 输出结果: # work1 nums = [10, 11, 12, 13, 14] # work2 nums = [10, 11, 12, 13, 14] 复制代码

以上代码中 work1 与 work2 虽然运行在两个进程中,但都可以访问和修改同一个 ShareableList 对象。

@cached_property

熟悉 Python Web 开发的同学,对 werkzeug.utils.cached_propertydjango.utils.functional.cached_property 这两个装饰器一定非常熟悉,它们是内置 @property 装饰器的加强版,被装饰的实例方法不仅变成了属性调用,还会自动缓存方法的返回值。

现在官方终于加入了自己的实现:

>>> import time >>> from functools import cached_property >>> class Example: ...     @cached_property ...     def result(self): ...         time.sleep(1) # 模拟计算耗时 ...         print('work 1 sec...') ...         return 10 ... >>> e = Example() >>> e.result work 1 sec... 10 >>> e.result # 第二次调用直接使用缓存,不会耗时 10



https://blog.sciencenet.cn/blog-252888-1207704.html

上一篇:[转载]多重假设检验与Bonferroni校正、FDR校正
下一篇:[转载]MILA 2018夏季深度学习与强化学习课程资源大放送
收藏 IP: 50.236.98.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-20 09:20

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部