python3.8的特性

Python 3.8正式发布,带来那些新特性

命名表达式 :=

「海象运算符」(The Walrus Operator)

pattern = re.compile('s')
data = 'ss'



match = pattern.match(data)
if match:
    print(match.group(0))
    
    
#  使用 := 

if (match := pattern.match(data)) is not None:
    print(match.group(0))


读取文件

while 1:
    line = fp.readline()
    if not line:
        break
    print(line)


while (line := fp.readline()):
    print(line)

列表表达式



data = ["apple", "banana", "candy", "arrange"]
results = []

def f(a):
    if (ret := a.startswith("a")):
        return f"pre_{a}"
#
# for x in data:
#     result = f(x)
#     if result:
#         results.append(result)

results = [
    y for x in data if (y := f(x))
]


print(results)





使用 / 强制, 位置参数

/左面的这些参数,只能是位置参数(不能是关键字参数):


def divmod1(x, y):
    return x // y

def divmod2(x, y, /):
    #  在/左面的这些参数,只能是位置参数(不能是关键字参数):
    return x // y

r = divmod1(1, 2)
r = divmod1(x=1, y=2)

r = divmod2(1, 2)

print(r)

Python Runtime Audit Hooks 运行时添加审计钩子


In : def audit_hook(event, args):
...:     if event in ['make_request']:
...:         print(f'Network {event=} {args=}')
...:

In : sys.addaudithook(audit_hook)

In : sys.audit('make_request', 'https://baidu.com')
Network event='make_request' args=('https://baidu.com',)

In : sys.audit('make_request', 'https://douban.com')
Network event='make_request' args=('https://douban.com',)

Multiprocessing shared memory 跨进程共享内存

跨进程直接访问同一内存 (共享):


# IPython进程A
In : from multiprocessing import shared_memory

In : a = shared_memory.ShareableList([1, 'a', 0.1])

In : a
Out: ShareableList([1, 'a', 0.1], name='psm_d5d6ba1b') # 注意name
# IPython进程B(另外一个终端进入IPython)
In : from multiprocessing import shared_memory

In : b = shared_memory.ShareableList(name='psm_d5d6ba1b')  # 使用name就可以共享内存

In : b
Out: ShareableList([1, 'a', 0.1], name='psm_d5d6ba1b')

importlib.metadata模块 可以直接读取第三方包的元数据:


In : from importlib.metadata import version, files, requires, distribution

In : version('flask')
Out: '1.1.1'

In : requires('requests')
Out:
['chardet (<3.1.0,>=3.0.2)',
 'idna (<2.9,>=2.5)',
 'urllib3 (!=1.25.0,!=1.25.1,<1.26,>=1.21.1)',
 'certifi (>=2017.4.17)',
 "pyOpenSSL (>=0.14) ; extra == 'security'",
 "cryptography (>=1.3.4) ; extra == 'security'",
 "idna (>=2.0.0) ; extra == 'security'",
 "PySocks (!=1.5.7,>=1.5.6) ; extra == 'socks'",
 'win-inet-pton ; (sys_platform == "win32" and python_version == "2.7") and extra == \'socks\'']

In : dist = distribution('celery')

In : dist.version
Out: '4.3.0'

In : dist.metadata['Requires-Python']
Out: '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'

In : dist.metadata['License']

In : dist.entry_points
Out:
[EntryPoint(name='celery', value='celery.__main__:main', group='console_scripts'),
 EntryPoint(name='celery', value='celery.contrib.pytest', group='pytest11')]

In : files('celery')[8]
Out: PackagePath('celery/__init__.py')

In : dist.locate_file(files('celery')[8])
Out: PosixPath('/Users/dongweiming/test/venv/lib/python3.8/site-packages/celery/__init__.py'

Buy me a 肥仔水!