8. The pathlib module
PEP 428 (3.4-)
Python3.3
Python3.4
8
>>> import os
>>> root_path = os.path.dirname(os.path.abspath(__file__))
>>> import pathlib
>>> root_path = pathlib.Path(__file__).resolve().parent
9. The pathlib module
PEP 428 (3.4-)
9
>>> data_path = pathlib.Path(‘data/csv‘)
>>> data_path.mkdir(parents=True, exist_ok=True)
>>> data_path = pathlib.Path('data')
>>> for filename in data_path.glob('**/*.csv'):
... print(filename)
data/csv/data1.csv
data/csv/data2.csv
10. Adding a file system path protocol
PEP 519 (3.6-)
buildin open() os.path
pathlib.Path
>>> import pathlib
>>> with open(pathlib.Path("README")) as f:
... contents = f.read()
...
3.6 pathlib
10
11. Type hints
PEP 484 (3.5-)
def greeting(name: str) -> str:
return 'Hello ' + name
__annotations__
print(greeting.__annotations__)
# {'name': <class 'str'>, 'return': <class 'str'>}
11
12. Postponed Evaluation of Annotations
PEP 563 (3.7-)
class C:
@classmethod
def from_string(cls, source: str) -> C:
…
import
from __future__ import annotations
12
13. > “mutable namedtuples with defaults”
Python
__init__, __repr__, __eq__, __ne__,
__lt__, __le__, __gt____ge__
Data Classes
PEP 557 (3.7-)
13
14. Data Classes
PEP 557 (3.7-)
14
from typing import List
class User:
name: str
age: int
items: List[int] = None
def __init__(self, name: str, age: int = 0):
self.name = name
self.age = age
self.items = []
def __repr__(self):
return f’{self.__class__.__name__}’
....
user = User('Taro', 10)
# procedue User(name='Taro', age=10, items=[])
15. Data Classes
PEP 557 (3.7-)
15
from dataclasses import dataclass, field
from typing import List
@dataclass
class User:
name: str
age: int
items: List[int] = field(default_factory=list)
user = User('Taro', 10)
# procedue User(name=‘Taro’, age=10, items=[])
16. Other especially update
• 3.6
• PEP 498 — Literal String Interpolation ←fstring
• 3.7
• PEP 553 — Built-in breakpoint()
• PEP 567 — Context Variables
16
18. Retirements of Guido van Rossum
18
I would like to remove myself entirely from the decision process.
I'll still be there for a while as an ordinary core dev,
and I'll still be available to mentor people -- possibly more available.
But I'm basically giving myself a permanent vacation from being BDFL,
and you all will be on your own.
Benevolent Dictator For Life (BDFL) — Guido van Rossum
19. What’s new in Python 3.8
PEP 569
• 2019 10
• PEP 572 — Assignment Expressions
19
20. Assignment Expressions
PEP 572 (3.8-)
• :=
•
match = pattern.match(data)
if match:
result = match.group(1)
•
if (match := pattern.search(data)) is not None:
result = match.group(1)
20
Pythonic