Outline

Because Python2 official maintenance period draws to a close, more and more Python project to switch from Python2 to Python3. However, in the actual work, I found a lot of people are thinking Python2 with the Python3 to write code, Python3 gives us a lot of new, very convenient features that can help us to quickly write code.

f-strings (3.6+)

. Python, we often use the function to format string format, for example:

1
2
3
4
5
6
7
8
9
10
user = "Jane Doe"
action = "buy"

log_message = 'User {} has logged in and did an action {}.'.format(
user,
action
)

print(log_message)
输出:User Jane Doe has logged in and did an action buy.

Python3 which provides a more flexible and convenient way to format strings, called f-strings. The above codes can be achieved:

1
2
3
4
5
6
user = "Jane Doe"
action = "buy"

log_message = f'User {user} has logged in and did an action {action}.'
print(log_message)
输出: User Jane Doe has logged in and did an action buy.

Pathlib (3.4+)

f-strings this feature too convenient, but for such a string of documents Road King, Python also provides a more convenient approach. Pathlib is a process files Road King Python3 provide libraries. E.g:

1
2
3
4
5
6
7
8
9
10
11
Import pathlib the Path from 

the root the Path = ( 'post_sub_folder')
Print (the root)
output: post_sub_folder

path = the root / 'happy_user'

# Road King absolute output
print (path.resolve ())
output: / root / post_sub_folder / happy_user

Type hinting (3.5+)

Static and dynamic type is a hot topic in software engineering, everyone has a different view, Python as a dynamically typed language, in Python3 Type hinting also provides features such as:

1
2
3
4
5
def sentence_has_animal(sentence: str) -> bool:
return "animal" in sentence

sentence_has_animal("Donald had a farm without animals")
# True

Enumerations (3.4+)

Enum class Python3 are provided so that you can achieve a capacity of enumerated type:

1
2
3
4
5
6
7
8
9
from enum import Enum, auto

class Monster(Enum):
ZOMBIE = auto()
WARRIOR = auto()
BEAR = auto()

print(Monster.ZOMBIE)
输出: Monster.ZOMBIE

Python3 of Enum also supports comparison and iteration.

1
2
3
4
5
6
for monster in Monster:
print(monster)

输出: Monster.ZOMBIE
Monster.WARRIOR
Monster.BEAR

Built-in LRU cache (3.2+)

Cache technology is now frequently used in the software field, Python3 provides a lru_cache decorator, to make better use of your cache. Instances below:

1
2
3
4
5
6
7
8
9
10
11
12
import time

def fib(number: int) -> int:
if number == 0: return 0
if number == 1: return 1

return fib(number-1) + fib(number-2)

start = time.time()
fib(40)
print(f'Duration: {time.time() - start}s')
# Duration: 30.684099674224854s

Now we can use to optimize our lru_cache above code, the code reduces the execution time.

1
2
3
4
5
6
7
8
9
10
11
12
13
from functools import lru_cache

@lru_cache(maxsize=512)
def fib_memoization(number: int) -> int:
if number == 0: return 0
if number == 1: return 1

return fib_memoization(number-1) + fib_memoization(number-2)

start = time.time()
fib_memoization(40)
print(f'Duration: {time.time() - start}s')
# Duration: 6.866455078125e-05s

Extended iterable unpacking (3.0+)

废话不多说,直接上代码,文档在这

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
head, *body, tail = range(5)
print(head, body, tail)
输出: 0 [1, 2, 3] 4

py, filename, *cmds = "python3.7 script.py -n 5 -l 15".split()
print(py)
print(filename)
print(cmds)
输出:python3.7
script.py
['-n', '5', '-l', '15']

first, _, third, *_ = range(10)
print(first, third)
输出: 0 2

Data classes (3.7+)

Python3提供data class装饰器来让我们更好的处理数据对象,而不用去实现 init() 和 repr() 方法。假设如下的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Armor:

def __init__(self, armor: float, description: str, level: int = 1):
self.armor = armor
self.level = level
self.description = description

def power(self) -> float:
return self.armor * self.level

armor = Armor(5.2, "Common armor.", 2)
armor.power()
# 10.4

print(armor)
# <__main__.Armor object at 0x7fc4800e2cf8>

使用data class实现上面功能的代码,这么写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from dataclasses import dataclass

@dataclass
class Armor:
armor: float
description: str
level: int = 1


def power(self) -> float:
return self.armor * self.level

armor = Armor(5.2, "Common armor.", 2)
armor.power()
# 10.4

print(armor)
# Armor(armor=5.2, description='Common armor.', level=2)

Implicit namespace packages (3.3+)

通常情况下,Python通过把代码打成包(在目录中加入init.py实现)来复用,官方给的示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
sound/                          Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py

在Python2里,如上的目录结构,每个目录都必须有init.py文件,一遍其他模块调用目录下的python代码,在Python3里,通过 Implicit Namespace Packages可是不使用__init__.py文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
sound/                          Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
equalizer.py
vocoder.py
karaoke.py

结语

这篇文章只列出了一下部分Python3的新功能,我希望这篇文章向您展示了部分您以前不知道的Python 3新功能,并且希望能帮助您编写更清晰,更直观的代码。

[原文链接](http://www.bugcode.cn/2019/05/20/python3_new_func/)