Python 3.7 – Cool New features

Welcome back, to Python! It’s time to discuss the cool new features shipped with Python 3.7. Here are some of my favorites:

cobra-1287036_1920

  • Data Classes
  • Built-in breakpoint
  • Typing module
  • Importing Data files

Data Classes

What is it? A new decorator: @dataclass

What’s new? It eases writing special methods in the class, like __init__(), __repr__(), and __eq__(. They are added automatically.

Example:

from dataclasses import dataclass, field
@dataclass(order=True)
class Test:
…field1: str
…field2: str

The following does not need an implementation of __repr__() in the class:

>>> t = Test("abc","xyz")
>>> t
Test(field1='abc', field2='xyz')
>>> t.field1
'abc'
>>> t.field2
'xyz'

Doesn’t need an implementation of __eq__ to do this:

>>> t1=Test("abc","xyz")
>>> t==t1
True
>>> t2=Test("a","b")
>>> t==t2
False

Breakpoint

What is it?  A built-in pdb.

What’s new? Not a new feature but simplifies using the debugger. Eliminates the necessity to import pdb.

Example:
def divide(a,b):
…breakpoint()
…return a/b

>>> divide(2,3)
> (3)divide()
(Pdb)

Old way of importing pdb:

def divide(a,b):
….import pdb; pdb.set_trace()
….return a/b

Typing module13541540425_63372041e1

What is it?  Annotations and Type hinting

What’s new? Function Annotations intend to provide a standard way of associating metadata to function arguments and return values.

  • The annotations module and typing module provide hints on arguments and return value of a function.
  • Annotations earlier worked only with names available in the current scope. i.e. Forward referencing was not supported.
  • Annotations are now evaluated when a module is imported.

Example:  

Creating the file py37anno.py:

from __future__ import annotations

class Try:
…def foo(name: str) -> ‘salutation’:
……print(f”Annotations Example for you {name}”)

importing the annotations and typing module:

>>> from py37anno import Try
>>> from __future__ import annotations
>>> Try.foo.__annotations__
{‘name’: ‘str’, ‘return’: “‘salutation’”}
>>> import typing
>>> typing.get_type_hints(Try.foo)
{‘name’: <class ‘str’>, ‘return’: ForwardRef(‘salutation’)}
>>> Try.foo(‘Shilpa’)
Annotations Example for you Shilpa

Importing Data Files

What is it? An optimized, easy and organized API for working with data files in a Project

What’s new? Eliminates the necessity of hard-coding data file-names. The importlib.resources module helps in locating, importing and reading from the data file.

Example:

A file lorem.txt exists in the data directory of the project which also contains the __init__.py file

>>> import os
>>> os.listdir(‘data’)                                     #output: files in the ‘data’ directory
[‘lorem.txt’, ‘__init__.py’, ‘__pycache__’]

>> from importlib import resources
>>> with resources.open_text(“data”,”lorem.txt”) as f:
….print(f.readlines())
….
[‘”Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.” n’]

A note on installing python 3.7:

Creating a new environment:

conda create -n py37 -c anaconda python=3.7

Upgrade in an existing python environment to 3.7 in Anaconda:

conda install -c anaconda python=3.7

Leave a comment