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 =
if match is not None:

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

if (match := is not None:

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 function parameter flag: /, to the left of the parameter indicating mark, 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)
>>> pow(x=5, y=3)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: pow() takes no keyword arguments

This is actually a pure Python code built-in functions to simulate existing C code to achieve similar functions, such as built-in function len ( ‘string’) can not use the keyword parameter passing parameters.

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('')
event = 'urllib.Request' args =( '' , None , {}, 'GET' )

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}')

In 3.8 a = symbol needs to be increased, and can result splicing operation expression:

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

This feature applies to official indicates Debug.

Asyncio asynchronous interactive mode

In previous versions of Python interactive mode (REPL), involves Asyncio asynchronous functions, often require the use (func ()) to perform.

In version 3.8, when using python -m asyncio enter interactive mode, you no longer need

>>> import asyncio
>>> async def test():
...     await asyncio.sleep(1)
...     return 'test'
>>> await 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.Queue or multiprocessing.Pipe, joined multiprocessing.shared_memory in version 3.8, the use of Python as a shared memory area of ​​the base object It offers 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, ))
    p2 = Process(target=work2, args=(share_nums, ))

# 输出结果:
# 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 ShareableList object.


Python Web developers are familiar with the students, both on werkzeug.utils.cached_property and django.utils.functional.cached_property decorator must be very familiar with, they are @property decorator built an enhanced version of an instance method is decorated not only become 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...
>>> e.result # 第二次调用直接使用缓存,不会耗时

Other improvements

    PEP 587: Python initial configuration

    PEP 590: Vectorcall, calling for rapid agreement of CPython

    finally: now allowed to continue to use

    typed_ast be merged back into CPython

    pickle now 4 protocol used by default, to improve performance

    LOAD_GLOBAL faster by 40%

    unittest added support for asynchronous

    On Windows, the default asyncio event loop is now ProactorEventLoop

    On macOS, multiprocessing start method is used by default spawn

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

This article belongs to original content, starting in micro-channel public number “life-oriented programming,” For reprint please leave a message in the public numbers background.

After the reply concerned the following information for more resources
    Reply [information] to obtain Python / Java and other learning resources
    Reply [plug-in] get reptile commonly used Chrome plugin
    [Reply] know almost get the latest simulation know almost Log

Leave a Reply