Python 3.8.0 official release, the new features first experience Full description

Python 3.8.0 official release, the new features first experience

Beijing on October 15, Python 3.8.0 official release of the official version, this version than the 3.7 version once again brought a number of very useful new features.

Assignment expression

PEP 572: Assignment Expressions

Add a new syntax: :=, also known as "walrus operator" (why is it called walrus, take a look at these two symbols look like color expression), if you used the Go language, should be very familiar with this syntax.

We directly with the specific role of examples to show, such as when using a regular match, the previous version, we will write the following:

import re

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

The use of an assignment expression, we can be rewritten as:

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

If statement also completed evaluation, assignment variable, which is determined three-step operation, again simplifying the code.

The following is a list of the usage in the expression:

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

Forced position parameters

PEP 570: Python Positional-Only parameters

Add a marker function parameter: /for a parameter indicating mark at the left, only receiving position parameter that is not a keyword parameter form.

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

This is actually built-in functions pure Python code to simulate existing C code to achieve similar functions, such as built-in function len('string')parameter passing keyword parameter can not be used.

Runtime Audit hook

PEP 578: Python Runtime Audit Hooks

This allows us to add some hooks for certain events and API, for parameters at runtime monitor events related.

For example, here listening urllib request:

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

Official built a number of API, specifically to see the PEP-578 specification document , you can also be customized.

f-strings support equal sign

Increase in the Python 3.6 version of f-strings, f can be used more easily formatted string prefix, while calculation, for example:

>>> x = 10
>>> print(f'{x+1}')
11

In 3.8 need to add a =symbol, you can concatenation expressions and results:

>>> x = 10
>>> print(f'{x+1=}')
'x+1=11'

This feature applies to official indicates Debug.

Asyncio asynchronous interactive mode

In previous versions of Python interactive mode (REPL), involves Asyncio asynchronous functions often necessary to use asyncio.run(func())in order to perform.

In the 3.8 version, when python -m asyncioentering the interactive mode, you no longer need asyncio.run.

>>> import asyncio
>>> async def test():
...     await asyncio.sleep(1)
...     return 'test'
...
>>> await test()
'test'

Cross-process shared memory

In Python multi-process, the communication between the different processes is a common problem, the usual approach is to use multiprocessing.Queueor multiprocessing.Pipeadded in the 3.8 version multiprocessing.shared_memory, use shared memory region dedicated to basic Python objects, providing a new option for interprocess communication .

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]

The above code work1 work2 although with two runs in the process, but they can access and modify the same ShareableListobject.

@cached_property

Python Web developers are familiar with the students on werkzeug.utils.cached_propertythe django.utils.functional.cached_propertytwo decorators must be very familiar with, they built @propertyan enhanced version of the decorator, instance method is decorated not only become the property call, the return value will automatically caching methods.

Now official finally joined their implementation:

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

Other improvements

  • PEP 587: Python initial configuration
  • PEP 590: Vectorcall, calling for rapid agreement of CPython
  • finally: Now allowed continue
  • typed_ast It is merged back into CPython
  • pickle 4 protocol now used by default, to improve performance
  • LOAD_GLOBAL 40% faster
  • unittest Added support for asynchronous
  • On Windows, the default is now asyncio event loop ProactorEventLoop
  • On macOS, multiprocessingstart using the default methodspawn

More specific changes can view the What's New In Python 3.8

Guess you like

Origin www.cnblogs.com/TMesh-python/p/11731503.html