MITB Banner

What’s New In Python 3.7.2: Look At 7 Features That You Should Know

Share

There’s a lot of new material in Python Latest version and much of it is pretty simple. For example, str, bytes and bytearray now have an isascii() function that returns ‘true’ if they only include ASCII characters.

In this article, we list down 7 essential features of the latest version which Python aspirants must get updated with.

Postponed Evaluation Of Annotations

The appearance of type hints in Python revealed two glaring usability concerns with the functionality of annotations which were added in the latest Python 3.7.2 version.

  • annotations could only handle names which were previously available in the current scope, in other words, they didn’t support foremost references of any kind, and
  • annotating source code had opposing impacts on startup time of Python programs.

Both of these problems are fixed by delaying the evaluation of annotations. Instead of compiling code which executes expressions in annotations at their rendering time, the compiler stores the annotation in a string form comparable to the AST of the expression in question. If needed, commentaries can be resolved at runtime using typing.get_type_hints(). In the common case where this is not needed, the annotations are inexpensive to store and make startup time quicker.

Usability-wise, annotations now carry forward references, making the subsequent syntax valid:

Code:

class D:
@classmethod
def from_string(cls, source: str) -> D:
...

def validate_b(self, obj: C) -> bool:

class C:

Since this change breaks adaptability, the new behaviour requires to be enabled on a per-module basis in Python 3.7 using a __future__ import:

Forced UTF-8 Mode

On programs other than Windows, there has always been a difficulty with the locale supporting UTF-8 or ASCII (7-bit) characters. The regular C locale is typically ASCII. This influences how text files are read (for instance). UTF-8 comprises all 8-bit ASCII characters and 2-4 length characters, as well. This change applies the locale to be one of the promoted UTF-8 locales. users can change what happens by introducing a new environment variable, PYTHONCOERCELOCALE. To practice ASCII requires both this setting and PYTHONUTF8 to be disabled. Setting PYTHONUTF8 to 1 force the Python interpreter to manage UTF-8, but if this isn’t described, it defaults to the locale setting; only if PYTHONCOERCELOCALE is disabled does it use ASCII mode. To explain technically, UTF-8 is not the default on Unix systems unless the user explicitly disables these two settings.

Built-in breakpoint()

With previous versions of Python, user’s could get a breakpoint by using the pdb debugger and this code, which breaks after function1() is described and before function2():

function1()
import pdb; pdb.set_trace()
function2()

The creator of PEP 553 found this a bit fiddly, and two statements on a line bothered some Python developers. So now there’s a unique breakpoint() function:

function1()
breakpoint()
function2()

This works in combination with the Python environment variable PYTHONBREAKPOINT. When Set to 0  the breakpoint does nothing. Address it a function and module value, and it will import the module and call it. The users can modify this programmatically at runtime; that’s very handy for having conditional breakpoints.

Data Classes

If users are storing data in classes, this latest feature clarifies things by generating boilerplate code for users.A data class is a normal Python class with the extension of a @dataclass decorator. It makes handling of Type hints, a new feature since Python 3.5 where users explain variables to provide a reference as to the type of variable. Users have to use this for domains in a data class.In the example below, we can see the: str after the variable name. That’s a type reference.If users want their data class to be permanent, just add (frozen=true) to the decorator. Here’s a simple example explicating an immutable data class. There’s not a lot of code in the class declaration; all the normal stuff is generated for users. The last two lines use the class and print out the occurrences:

Code:

from dataclasses import dataclass

@dataclass(frozen=True)
class ReadOnlyStrings(object):

field_name : str
field_address1 : str
test = {ReadOnlyStrings(1,’Damodar’), ReadOnlyStrings(2,’Bhagat’)}
print(test)

Output:

{ReadOnlyStrings(field_name=2, field_address1=’Bhagat’),

ReadOnlyStrings(field_name=1, field_address1=’Damodar’)}

Core Support for typing module and Generic Types

The previous Python Version was composed in such a way that it would not include any changes to the core CPython interpreter. Now type hints and the typing module are widely used by the community, so this restriction is eliminated. The PEP introduces two special methods __class_getitem__() and mro_entries, these classifications are now used by most classes and special constructs in typing. As a consequence, the speed of different operations with types extended up to 7 times, the nonexclusive types can be used without metaclass conflicts, and various long-standing bugs in typing module are fixed.

Development Runtime Mode

The -X parameter of CPython which is the standard implementation of Python which lets the users set multiple implementation specifications, and has been extended to incorporate the word ‘dev.’ This activates new runtime checks such as debug hooks on memory allocators, lets the faulthandler module dump the Python traceback, and allows asyncio debug mode a mode which attaches extra logging and warnings but reduces asyncio performance. users program can identify if it’s running dev mode by checking sys.flags.dev_mode.

Code:

python -X dev
Python 3.7.0 (default, Jan 21  2019, 16:40:07)
[GCC 7.3.0] on (any operating system)
Type "help", "copyright", "credits" or "license" for additional information.

>> import sys
>> print (sys.flags.dev_mode)
True

Hash-Based .pyc Files

Python has traditionally terminated the up-to-dateness of bytecode cache files (i.e., .pyc files) by connecting the source metadata with authorisation metadata saved in the cache file header when it was produced. While active, this invalidation method has its disadvantages. When filesystem timestamps are too inferior, Python can miss source updates, leading to user confusion. Additionally, having a timestamp in the cache file is uncertain for build reproducibility and content-based build regularities. The new Python feature extends the pyc format to concede the hash of the source file to be accepted for invalidation instead of the source timestamp. Such .pyc files are described as hash-based. By default, Python still practices timestamp-based invalidation and does not generate hash-based .pyc files at runtime. Hash-based .pyc files may be created with py_compile or compileall. Hash-based .pyc files appear in two variants: checked and unchecked. Python validates checked hash-based .pyc files versus the identical source files at runtime but doesn’t do so for unchecked hash-based pycs. Unchecked hash-based .pyc files are a valuable performance optimization for environments where a system outside to Python is responsible for managing .pyc files up-to-date.

 

 

 

 

 

PS: The story was written using a keyboard.
Share
Picture of Bharat Adibhatla

Bharat Adibhatla

Bharat is a voracious reader of biographies and political tomes. He is also an avid astrologer and storyteller who is very active on social media.
Related Posts

CORPORATE TRAINING PROGRAMS ON GENERATIVE AI

Generative AI Skilling for Enterprises

Our customized corporate training program on Generative AI provides a unique opportunity to empower, retain, and advance your talent.

Upcoming Large format Conference

May 30 and 31, 2024 | 📍 Bangalore, India

Download the easiest way to
stay informed

Subscribe to The Belamy: Our Weekly Newsletter

Biggest AI stories, delivered to your inbox every week.

AI Courses & Careers

Become a Certified Generative AI Engineer

AI Forum for India

Our Discord Community for AI Ecosystem, In collaboration with NVIDIA. 

Flagship Events

Rising 2024 | DE&I in Tech Summit

April 4 and 5, 2024 | 📍 Hilton Convention Center, Manyata Tech Park, Bangalore

MachineCon GCC Summit 2024

June 28 2024 | 📍Bangalore, India

MachineCon USA 2024

26 July 2024 | 583 Park Avenue, New York

Cypher India 2024

September 25-27, 2024 | 📍Bangalore, India

Cypher USA 2024

Nov 21-22 2024 | 📍Santa Clara Convention Center, California, USA

Data Engineering Summit 2024

May 30 and 31, 2024 | 📍 Bangalore, India