Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the advantages of the new features of Python 3.8

2025-01-16 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 advantages of the new features of Python 3.8". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the advantages of the new Python 3.8features"?

Python is the latest version of the popular language for everything from automated scripting to machine learning to Web development. Now available in the official beta, Python 3.8brings many flexible syntax changes, memory sharing, more efficient serialization and deserialization, modified dictionaries, and more.

Of course, Python 3.8 also leads to a variety of performance improvements. The overall result is to make Python faster, more concise, more consistent, and more modern. The following is the latest and most important content in Python 3.8.

Assignment expression

The most obvious change in Python 3.8is the assignment expression, which uses the walrus-like operator (: =). Assignment expressions allow values to be assigned to variables, even variables that do not already exist, in the context of the expression, rather than as separate statements.

1. While (line: = file.readline ())! = "end": 2.print (chunk)

In this example, if the variable row does not exist, create the variable row and then assign the value from file.readline (). Then check the line to see if it equals "end". If not, the next row is read, stored in the line, tested, and so on.

Assignment expressions follow the tradition of understandable simplicity in Python, including list derivation. The idea here is to reduce some of the tedious templates that tend to appear in some Python programming patterns. For example, the above code snippet usually requires more than two lines of code to express.

Force some parameters to be only positions

The new syntax for function definition, which is only positional parameters, allows developers to force certain parameters to be positional only. This eliminates any ambiguity about which parameters in the function definition are positional and which are keyword arguments.

Only position parameters can define the scene, for example, a function accepts any keyword parameter but can also accept one or more locations. This is usually the case with Python built-in functions, so it provides a way for Python developers to enhance language consistency. If you are still confused in the world of programming and don't know your future plans, you can join our Python autumn dress to lose 784 words and 758 words to see how your predecessors learned! Exchange experiences! I am a senior python development engineer, from basic python scripts to web development, crawlers, django, data mining, etc., zero foundation to project actual combat materials have been sorted out. To every little friend of python! Share some learning methods and small details that need to be paid attention to

An example in the Python document:

1. Def pow (x, y, z=None, /): 2. R = x birthday 3. If z is not None: 4. R% = z 5. Return r

/ separate the position from the keyword argument; in this case, all the parameters are positional. In previous versions of Python, z would be treated as a keyword parameter. Given the above function definition, pow (2mag10) and pow (2mag10) are valid calls, but pow (2mag10 z = 5) is not.

F string debugging support

The f-string format provides a convenient (and more performance) way to print text and calculated values or variables in the same expression:

1. X = 32. Print (f'{xylene 1}')

This will print 4.

Adding = to the end of the f string expression prints the text of the f-string expression itself, followed by the value:

1. X = 32. Print (f'{xylene 1 =}')

This prints x + 1 = 4.

Shared memory of multi-processing modules

With Python 3.8, the multiprocessing module now provides a SharedMemory class that allows memory regions to be created and shared between different Python processes.

In previous versions of Python, data could only be shared between processes by writing data to a file, sending it over a network socket, or serializing it using Python's pickle module. Shared memory provides a faster path for passing data between processes, allowing Python to use multiple processors and processor cores more efficiently.

Shared memory segments can be allocated as raw areas of bytes, or they can use immutable list-like objects that store a small portion of Python objects-numeric types, strings, byte objects, and None objects.

Improvement of typing module

Python is dynamically typed, but supports the use of type hints through input modules to allow third-party tools to validate Python programs. Python 3.8 adds new elements for typing to check more reliably:

Final decorator and Final type annotation indicate that decorated/annotated objects should not be overwritten, subclassed, or redistributed anywhere.

The Literal type restricts an expression to a specific value or list of values, not necessarily of the same type.

The TypedDict type allows you to create dictionaries where the values associated with certain keys are limited to one or more specific types. Note that these restrictions are limited to what can be determined at compile time, not at run time.

New version of pickle protocol

Python's pickle module provides a way to serialize and deserialize Python data structures, for example, by allowing dictionaries to be saved as is to a file and reloaded later. Different versions of Python support different levels of pickle protocol, and newer versions support a wider range of features and more efficient serialization.

Version 5 of pickle, introduced with Python 3.8, provides a new way to pickle objects that implement Python buffer protocols, such as bytes, memory views, or NumPy arrays. The new pickle reduces the number of memory copies that must be made for these objects.

External libraries like NumPy and Apache Arrow support the new pickle protocol in their Python bindings. The new pickle is also available as an attachment to PyPI's Python 3.6 and Python 3.7.

Reversible dictionary

Dictionaries in Python are rewritten entirely in Python 3.6, using the new implementation provided by the PyPy project. In addition to being faster and more compact, dictionaries now have the inherent order of their elements; they are ordered when they are added, just like lists. Python 3.8allows the use of reversed () in dictionaries.

Performance improvement

Many built-in methods and functions have accelerated by 20% to 50%, because many of them unnecessarily convert the parameters passed to them.

The new opcode cache can speed up some instructions in the interpreter. However, the only acceleration achieved so far is for LOAD_GLOBAL opcodes, which is now 40% faster. Similar optimizations are planned for a later version of Python.

File copy operations, such as shutil.copyfile () and shutil.copytree (), now use platform-specific calls and other optimizations to speed up operations.

Because the optimization takes advantage of the length of the list constructor object (if known in advance), the newly created columns now behave an average of 12% smaller than before.

In Python 3.8, it is much faster to write class variables on a new class (for example, class A (object)).

Operator.itemgetter () and collections.namedtuple () also have new speed optimizations.

Python C API and CPython improvement

In the latest version of Python, the main work is to ReFactor C API used in CPython, which is a reference implementation of Python written in C. So far, this work has only produced incremental changes, but they are adding up:

The new C API for Python initialization configuration allows tighter control and more detailed feedback on Python initialization routines. This makes it easier to embed the Python runtime into the application and programmatically pass the startup parameters to Python. The new API is also designed to ensure that all Python configuration controls have a single, consistent home page to make future changes (such as Python's new UTF-8 mode) easier to insert.

Another new C API for CPython, the "vectorcall" invocation protocol, allows internal Python methods to be called more quickly without creating temporary objects to handle calls. API is still unstable, but temporarily available. The plan is to finalize it from Python 3.9.

The Python runtime audit hook provides two API in the Python runtime to hook events and enable them to observe external tools such as the test framework or logging and audit systems.

At this point, I believe you have a deeper understanding of "what are the advantages of the new features 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report