analitics

Pages

Wednesday, July 10, 2019

Python 3.7.3 : About python version 3.7.3.

All versions of python come with many features and changes with every released version.
A full list of these changes can be found at PEP official webpage and this documentation webpage.
The goal of these tutorials is to fix the learning area by each python version and have a good picture of these features.
Let's start with the first step - python modules.
Several of the standard library Python packages have been reorganized or moved with a few notable changes:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> import profile
>>> import urllib
>>> import urllib3
The division math operation has new features to explicitly convert integers to floats when working with integer variables:
>>> one = 1
>>> two = 2
>>> three = 3
>>> float(three)
3.0
>>> one/two
0.5
>>> one//three
0
>>> one//two
0
>>> float(one)/three
0.3333333333333333
>>>
You can use the pathlib library which provides the Path() object to fulfill all your path manipulation needs.
>>> from pathlib import Path
>>> folder1 = Path('/folder1')
>>> config_path = folder1 / 'subfolder1'
>>> config_path
WindowsPath('/folder1/subfolder1')
>>> str(config_path)
'\\folder1\\subfolder1'
>>> config_path.name
'subfolder1'
You can use operators with matrix:
>>> import numpy as np
>>> x = np.array([[11, 33], [22, 55]])
>>> y = np.array([[1, 3], [2, 5]])
>>> x @ y
array([[ 77, 198],
       [132, 341]])
>>> x * y
array([[ 11,  99],
       [ 44, 275]])
The list and dictionaries can easily be emptied using the .clear method:
>>> my_list = ['a','b','c']
>>> my_list.clear()
The print function is changed.
>>> print('hello')
hello
>>> a = ''
>>> f = open('my_file.txt', 'w')
>>> print(a, file=f)
>>> f.close()
The function annotations can provide information on inputs/outputs:
>>> def a_to_b(x: str) -> str:
...     return x.replace('a','b')
...
>>> a_to_b("abcdcba!?!")
'bbcdcbb!?!'
Fix the sensible comparison:
>>> 'True' > True
Traceback (most recent call last):
  File "", line 1, in 
TypeError: '>' not supported between instances of 'str' and 'bool'
With Python 3.6 we have a new type of strings: f-strings and string interpolation:
>>> var = 76/3
>>> f'The value is {var}.'
'The value is 25.333333333333332.'
You can use underscores in numbers:
>>> int_a = 1_000_000_000
>>> hex_b = 0b_0011_1111_0100_1110
>>> print(int_a,hex_b)
1000000000 16206
The new Unicode strings and variable (including emoji) names to be used.
An LRU cache decorator for your functions: functools.lru_cache.
An enumerated type in the standard library: Enum.
Use the standard ipaddress:
>>> import ipaddress
>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.ip_address('2001:db8::')
IPv6Address('2001:db8::')
In Python 3, decimals are rounded to the nearest even number (.5).
The input() function was fixed in Python 3 so that it always stores the user inputs as str objects.
In Python 3, the range() was implemented like the xrange() in older version.
That range got a new __contains__ method in Python 3.x.
You can simply convert the iterable object into a list via the list() function.
>>> print(range(3))
range(0, 3)
>>> print(type(range(3)))

>>> print(list(range(3)))
[0, 1, 2]
With advanced unpacking and range you can do this:
>>> a, b = range(2)
>>> print(a,b)
0 1
>>> a, b, *rest = range(6)
>>> print(a,b)
0 1
>>> print(rest)
[2, 3, 4, 5]
>>> a, *rest, b = range(6)
>>> print( a,b, rest)
0 5 [1, 2, 3, 4]
Get the first and the last of the open file with:
first, *_, last = f.readlines()
Keyword only arguments can be done with:
def f(a, b, *args, option=True):
The only way to access it is to explicitly call f(a, b, option=True).
If you don't want to collect *args the use this:
def f(a, b, *, option=True):
You can just use os.stat(file, follow_symlinks=False) instead of os.lstat.
The next function can be call only into this way:
>>> my_generator = (letter for letter in 'abcd')
>>> next(my_generator)
'a'
>>> next(my_generator)
'b'
The for-loop variables don’t leak into the global namespace anymore:
>>> i = 1
>>> print('comprehension:', [i for i in range(6)])
comprehension: [0, 1, 2, 3, 4, 5]
>>> print('i is ', i)
i is  1
The async and await are now reserved keywords.
More useful exceptions and also change the comma with the keyword as:
>>> try:
...     f = open('my_file.txt')
... except OSError as e:
...     if e.errno == errno.ENOENT:
...             #

...     else:

...     raise 
In Python 3, the .keys() method instead returns an iterator object instead of a list.
>>> my_dict = {'a': 11, 'b': 12, 'c': 13, 'd': 14}
>>> my_dict.keys()
dict_keys(['a', 'b', 'c', 'd'])
>>> my_dict_keys=list(my_dict.keys())
>>> my_dict_keys[3]
'd'
>>> my_dict.keys()[3]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'dict_keys' object is not subscriptable
Keyword-only arguments and positional parameters are valid in Python 3.7.3.
The chained Exceptions provide by python 3.7.3 has more information and the original exception is printed out, along with the original traceback.
>>> raise exception from e
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'exception' is not defined
>>> raise NotImplementedError from OSError
OSError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "", line 1, in 
NotImplementedError
These were briefly some information about python 3.7.3 that might be of use to you.