I touched some of the new features of Python 3.8 ①

Introduction

Weakly Python engineers have tried out some of the new features in python3.8. I'm skipping things I don't understand (I'm skipping builds and profiles). For details, refer to the official document [https://docs.python.org/ja/3/whatsnew/3.8.html)

Walrus operator

As part of the larger syntax, a new syntax: = has been added to assign values to variables. This syntax resembles a walrus eye and fangs, hence the nickname "walrus operator."

image.png Walrus operator cute </ font>

array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# python3.8 or earlier
# n = len(array) > 10
# if n:
#     print(f"List is too long ({n} elements, expected <= 10)")

# python3.8
if n := len(array) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

Output result

List is too long (True elements, expected <= 10)

Feeling that you can declare variables with judgment ??

It can also be used in while statements and comprehensions, so see the official document for details (https://docs.python.org/ja/3/whatsnew/3.8.html)

Position-only arguments

Added new syntax / to indicate that function arguments must be specified as positional arguments and cannot be specified as keyword arguments. This syntax is the same as when help () displays the C function annotated by Larry Hasting's Argument Clinic.

Correct function call

def profile(first_name, last_name, /, gender, age, *, zip_code, address):
    print(f'\
Surname:{first_name}\n\
Name:{last_name}\n\
sex:{gender}\n\
age:{age}\n\
        〒:{zip_code}\n\
Housing:{address}')

profile('Suzuki', 'Ichiro', 'Man', 99, zip_code='000-0000', address='space')  # OK
profile('Suzuki', 'Ichiro', 'Man', age=99, zip_code='000-0000', address='space')  # OK
profile('Suzuki', 'Ichiro', gender='Man', age=99, zip_code='000-0000', address='space')  # OK

The arguments are in order from the left Positional arguments: first_name, last_name It's both a positional argument and a keyword argument: gender, ʻage Keyword arguments:zip_code, ʻaddress

Wrong function call

profile('Suzuki', 'Ichiro', gender='Man', 99, zip_code='000-0000', address='space')  # SyntaxError: positional argument follows keyword argument
profile('Suzuki', 'Ichiro', age=99, 'Man', zip_code='000-0000', address='space')  # SyntaxError: positional argument follows keyword argument
profile('Suzuki', 'Ichiro', 'Man', 99, '000-0000', address='space')  # TypeError: profile() takes 4 positional arguments but 5 positional arguments (and 1 keyword-only argument) were given
profile('Suzuki', 'Ichiro', 'Man', 99, zip_code='000-0000', 'space')  # SyntaxError: positional argument follows keyword argument

Eliminate use as a keyword argument

Arguments before / are positional arguments, so it is now possible to eliminate the following calling methods that were possible before python3.8. You can force it as a positional argument, so you can change the argument name without hesitation !!! </ red>

# python3.Prior to 8, it could be used as both a positional argument and a keyword argument.
def profile(first_name, last_name):
    print(f'{first_name} {last_name}')
profile2(first_name='Yoshida', last_name='Hanako')  # Yoshida Hanako
...
..
.
# python3.8 position-only arguments/use
def profile(first_name, last_name, /):
    print(f'{first_name} {last_name}')
profile2(first_name='Yoshida', last_name='Hanako')  # TypeError: profile2() got some positional-only arguments passed as keyword arguments: 'first_name, last_name'

You can also write it like this to receive arbitrary keyword arguments.

def profile(first_name, last_name, /, **kwargs):
    print(f'{first_name} {last_name} {kwargs}')
profile('Yoshida', 'Hanako', first_name='Suzuki', last_name='Ichiro')  # Yoshida Hanako {'first_name': 'Suzuki', 'last_name': 'Ichiro'}

This makes it much simpler to define a function or method that accepts arbitrary keyword arguments.

It is officially said, but I am a weak engineer so I do not understand the taste.

Ability to store cache files in another location

The implicit bytecode cache uses the pycache subdirectory within each source code directory by default, but with the newly added environment variable PYTHONPYCACHEPREFIX (or the command line option -X pycache_prefix), the source code and It will now be stored in a separate directory tree.

The cache location can be found in sys.pycache_prefix (when using pycache it would be: const: None).

I couldn't verify it well, so I went through it for the time being. .. ..

The "=" specifier is now enabled in formatted string literals (f-string)

string = 'F string'

# python3.8.Before 0
print(f'{string}')  #F string

# python3.8.0
print(f'{string=}')  # string='F string'

It seems to be useful for debugging (small average feeling)

dict and dictview can now iterate in reverse order using reversed ()

Up to python3.7, if you try to reverse dict with reversed, you will get TypeError:'dict' object is not reversible.

# python3.8.Before 0
dictionary = {'a': 1, 'b': 2, 'c': 3}

for d in reversed(dictionary):
    print(d)

>> TypeError: 'dict' object is not reversible

Starting with python3.8, that's possible!

# python3.8.Before 0
dictionary = {'a': 1, 'b': 2, 'c': 3}

for d in reversed(dictionary):
    print(d)

>> c
>> b
>> a

The _asdict () method of collections.namedtuple () now returns a dict

How to do named tuple in the first place [here](https://qiita.com/Seny/items/add4d03876f505442136#%E3%81%A9%E3%82%93%E3%81%AA%E3%81% A8% E3% 81% 8D% E3% 81% ABnamedtuple% E3% 82% 92% E4% BD% BF% E3% 81% 86% E3% 81% 8B) has an easy-to-understand explanation !!!

Prior to python3.8, it returned ʻOrderedDict`.

import collections
Human = collections.namedtuple('Human', ['first_name', 'last_name', 'age'])
human = Human('yamada', 'taro', 25)
print(human._asdict())

>> OrderedDict([('first_name', 'yamada'), ('last_name', 'taro'), ('age', 25)])

python3.8 now returns Dict!

import collections
from collections import OrderedDict

Human = collections.namedtuple('Human', ['first_name', 'last_name', 'age'])
human = Human('yamada', 'taro', 25)
print(human._asdict())
# print(OrderedDict(human._asdict()))  # 3.Even with 8, if you want to use the functions specific to Ordered Dict, it is recommended to cast and use it.

>> {'first_name': 'yamada', 'last_name': 'taro', 'age': 25}

csv.DictReader now also returns dict

This change allows you to run faster and with less memory usage while maintaining order.

It seems. I did it.

Two methods added to datetime module

Added methods datetime.date.fromisocalendar () and datetime.datetime.fromisocalendar () to create date and datetime objects, depending on the year, week number, and day of the week according to ISO regulations; this is for each class. It is the reverse of the isocalendar method.

what the hell? I tried to output it.

from datetime import datetime

date = datetime.now()  # 2020-03-06(Hours, minutes and seconds omitted)
print(date.isocalendar())  # (2020, 10, 5)
print(date.fromisocalendar(2020, 4, 1))  # 2020-01-20 00:00:00
print(datetime.fromisocalendar(2020, 4, 1))  # 2020-01-20 00:00:00

First of all, the existing isocalendar ()

2020-03-06 is 2020, 10th week Friday (5) day of the week </ font> image.png

From isocalendar added in 3.8

print(date.fromisocalendar(2020, 4, 1)) # 2020-01-20 00:00:00 The details of the arguments are from left to right: AD, week, day of the week`

`` 2020 4th week Monday (1) day of the week </ font>

image.png

① ends here

I'm tired, so I'm done. ② will be released soon. (Self-satisfaction)

Recommended Posts