summarize
By 2020, the official maintenance period of Python2 will come to an end, and more and more Python projects are switching from Python2 to Python3. In fact, in practice, many partners are still using Python2 thinking to write Python3 code. I'll summarize some of the new and more convenient features of Python3 for you! I hope you can also write code efficiently after reading this!
f-strings (3.6+)
Inside Python, we often use the format function to format strings, for example:
user = "Jane Doe"action = "buy"log_message = 'User {} has logged in and did an action {}.'.format( user, action)print(log_message)exports:User Jane Doe has logged in and did an action buy.
Python 3 provides a more flexible and convenient way to format strings, called f-strings, which can be implemented like this.
user = "Jane Doe"action = "buy"log_message = f'User {user} has logged in and did an action {action}.'print(log_message)exports: User Jane Doe has logged in and did an action buy.
Pathlib (3.4+)
The f-strings feature is so convenient, but for strings like file pathlib, Python also provides a more convenient way to handle them.Pathlib is a library provided by Python3 to handle file pathlib. For example:
from pathlib import Pathroot = Path('post_sub_folder')print(root)output result: post_sub_folder path = root / 'happy_user'# The output is absolutely rock solid.print(())output result:/root/post_sub_folder/happy_user
Type hinting (3.5+)
Static vs. dynamic typing is a hot topic in software engineering and everyone has a different opinion, Python as a dynamically typed language also provides Type hinting functionality in Python 3, e.g..
def sentence_has_animal(sentence: str) -> bool: return "animal" in sentence sentence_has_animal("Donald had a farm without animals")# True
Enumerations (3.4+)
Python3 provides the Enum class that lets you implement an enum type very easily:
from enum import Enum, autoclass Monster(Enum): ZOMBIE = auto() WARRIOR = auto() BEAR = auto()print()exports:
Python3's Enum also supports comparison and iteration.
for monster in Monster: print(monster)exports:
Built-in LRU cache (3.2+)
Caching is a frequently used technique in software these days, and Python 3 provides a lru_cache decorator to let you use caching better. Here's an example:
import timedef fib(number: int) -> int: if number == 0: return 0 if number == 1: return 1 return fib(number-1) + fib(number-2)start = ()fib(40)print(f'Duration: {() - start}s')# Duration: 30.684099674224854s
Now we can use lru_cache to optimize our code above and reduce the code execution time.
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 = ()fib_memoization(40)print(f'Duration: {() - start}s')# Duration: 6.866455078125e-05s
Extended iterable unpacking (3.0+)
The code is as follows:
head, *body, tail = range(5)print(head, body, tail)exports: 0 [1, 2, 3] 4py, filename, *cmds = "python3.7 -n 5 -l 15".split()print(py)print(filename)print(cmds)exports:python3.7 ['-n', '5', '-l', '15']first, _, third, *_ = range(10)print(first, third)exports: 0 2
Data classes (3.7+)
Python3 provides data class decorators to allow us to work with data objects without having to implement the init() and repr() methods. Assume the following code.
class Armor: def __init__(self, armor: float, description: str, level: int = 1): = armor = level = description def power(self) -> float: return * armor = Armor(5.2, "Common armor.", 2)()# 10.4print(armor)# <__main__.Armor object at 0x7fc4800e2cf8>
The code that implements the above functionality using the data class is written like this.
from dataclasses import dataclass@dataclassclass Armor: armor: float description: str level: int = 1 def power(self) -> float: return * armor = Armor(5.2, "Common armor.", 2)()# 10.4print(armor)# Armor(armor=5.2, description='Common armor.', level=2)
Implicit namespace packages (3.3+)
Typically, Python reuses code by packaging it up (by adding init .py to the directory), the official example given is as follows.
sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py ... effects/ Subpackage for sound effects __init__.py ... filters/ Subpackage for filters __init__.py
In Python 2, with the directory structure as above, each directory must have an init .py file, so that other modules can call the python code in the directory again. In Python 3, the __init__.py file can be dispensed with through Implicit Namespace Packages.
sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions ... effects/ Subpackage for sound effects ... filters/ Subpackage for filters
concluding remarks
Here is only a partial list of Python 3's new features due to time constraints (it's really quite busy), and I hope that after reading this article, you will learn and use it to write clearer and more intuitive code!
This is the whole content of this article.