In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "what are the functions of Python 3.8". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the functions of Python 3.8"?
New assignment expression
The title of PEP 572is an assignment expression, also known as a "named expression", but it is now widely nicknamed "walrus operator" (The Walrus Operator). Because: very much like walrus "small eyes, with two long teeth" this characteristic ^ _ ^.
Here is an example of how to implement the Fibonacci sequence through a row rewritten in PEP 572:
In: (lambda f: F, int (input ('Input:'), 1,0,1)) (lambda f, t, I, a, b: print (f'fib ({I}) = {b}') or t = i or f...: (f, t, I + 1, b) A + b)) Input: 10 fib (1) = 1 fib (2) = 1 fib (3) = 2 fib (4) = 3 fib (5) = 5 fib (6) = 8 fib (7) = 13 fib (8) = 21 fib (9) = 34 fib (10) = 55 Out: True
Rewrite based on Raymond Hettinger version:
In: [(In = (t [1], sum (t)) if i else (0Jing 1)) [1] for i in range (10)] Out: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Force the use of location parameters
To put it bluntly, PEP 570s force users to use location parameters.
Warm reminder: under the Python3.8 version, you see the following error:
TypeError: divmod () takes no keyword arguments
That's the reason!
Add audit hooks at run time
You can now add audit hooks to the Python runtime:
In: import sys...: import urllib.request...: def audit_hook (event Args):...: if event in ['urllib.Request']:...: print (f'Network {event=} {args=}')...: sys.addaudithook (audit_hook) In: urllib.request.urlopen ('https://httpbin.org/get?a=1') Network event='urllib.Request' args= (' https://httpbin.org/get?a=1', None, {}) 'GET') Out:
Currently, the event names and API that support auditing can be found in the PEP document (extended read link 2), and urllib.Request is one of them. You can also customize events:
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',)
Cross-process memory sharing
You can access the same memory directly across processes (shared):
# IPython process An In: from multiprocessing import shared_memory In: a = shared_memory.ShareableList ([1, 'axiom, 0.1]) In: an Out: ShareableList ([1,' axiom, 0.1] Name='psm_d5d6ba1b') # Note name # IPython process B (another terminal enters IPython) In: from multiprocessing import shared_memory In: B = shared_memory.ShareableList (name='psm_d5d6ba1b') # using name, you can share memory In: B Out: ShareableList ([1, 'axiom, 0. 1], name='psm_d5d6ba1b')
New third-party packet reading module
Using the new importlib.metadata module, you can directly read the metadata of third-party packages:
In: from importlib.metadata import version, files, requires, distribution In: version ('flask') Out:' 1.1.1' In: requires ('requests') Out: [' chardet (= 3.0.2)', 'idna (= 2.5)', 'urllib3 (! = 1.25.0),' 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.31,! = 3.1.31,! = 3.2.* ! = 3.3.The 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')
Add cache properties
Cached_property is a very common feature, and many well-known Python projects have implemented it on their own, and now they have finally entered the version library.
Functools.lru_cache can be used as a decorator without parameters.
The lru_cache decorator supports max_size and typed2 parameters. If you are not sensitive to the default parameters, you can only use them in the past (empty parentheses are required):
In: @ lru_cache ()...: def add (a, b):...: return a + b...:
Starting from 3.8, it can be used directly as a decorator, rather than as a function that returns the decorator (without parentheses):
In: @ lru_cache...: def add (a, b):...: return a + b...:
Like dataclasses.dataclass, most scenarios use this:
@ dataclass class InventoryItem:...
Actually, dataclass supports multiple parameters:
Def dataclass (cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False):
So in this use of a decorator factory that uses all the default values, parentheses are superfluous.
Asyncio REPL
REPL is very helpful for learning a new programming language, and you can quickly verify your understanding through output in this interactive environment.
The official has added a new Asyncio REPL function, which is more convenient to use!
F-strings DEBUG
A new debugging feature, of course, is consistent and does not help debugging.
Async Mock
The unit test module unittest adds classes for mock asynchronous code:
In: import asyncio In: from unittest.mock import AsyncMock, MagicMock In: mock = AsyncMock (return_value= {'json': 123}) In: await mock () Out: {' json': 123} In: asyncio.run (mock () Out: {'json': 123} In: async def main (* args, * * kwargs):.: return await mock (* args * * kwargs).: In: asyncio.run (main ()) Out: {'json': 123} In: mock = MagicMock () # AsyncMock or In: mock.__aiter__.return_value = [1,2,3] In: async def main ():.: return [i async for i in mock].: In: asyncio.run (main () Out: [1,2,3]
Iterative unpacking
This is mainly to fix the problem.
At this point, I believe you have a deeper understanding of "what are the functions of Python 3.8?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.