Get a brief look at some new features in Python3

  • 2021-07-18 08:12:26
  • OfStack

Overview

By 2020, the official maintenance period of Python2 will end, and more and more Python projects will be switched from Python2 to Python3. In fact, in practical work, many partners are still writing Python3 code with Python2 thinking. Summarize some new and more convenient features of Python31 for everyone! I hope you can write the code efficiently after reading it.

f-strings (3.6+)

In Python, we often use the format function to format strings, such as:


user = "Jane Doe"action = "buy"log_message = 'User {} has logged in and did an action {}.'.format(
 user,
 action)print(log_message) Output: User Jane Doe has logged in and did an action buy.

Python3 provides a more flexible and convenient way to format strings, called f-strings. The above code can be implemented as follows:


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

Pathlib (3.4+)

f-strings is very convenient, but Python also provides a more convenient way to deal with strings such as file path strength. Pathlib is a file processing library provided by Python3. For example:


from pathlib import Pathroot = Path('post_sub_folder')print(root) Output result : post_sub_folder
path = root / 'happy_user'#  Output absolute road strength print(path.resolve()) Output: /root/post_sub_folder/happy_user

Type hinting (3.5+)

Static and dynamic types are a hot topic in software engineering, and everyone has different views. As a dynamic type language, Python also provides Type hinting functions in Python3, such as:


def sentence_has_animal(sentence: str) -> bool:
 return "animal" in sentence
sentence_has_animal("Donald had a farm without animals")# True

Enumerations (3.4+)

The Enum class provided by Python3 allows you to implement one enumeration type very easily:


from enum import Enum, autoclass Monster(Enum):
  ZOMBIE = auto()
  WARRIOR = auto()
  BEAR = auto()print(Monster.ZOMBIE) Output : Monster.ZOMBIE

Enum of Python3 also supports comparison and iteration.


for monster in Monster:
  print(monster) Output : Monster.ZOMBIE   Monster.WARRIOR   Monster.BEAR

Built-in LRU cache (3.2+)

Caching is a common technology in the software field nowadays. Python3 provides an lru_cache decorator to make you better use of caching. 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 = time.time()fib(40)print(f'Duration: {time.time() - start}s')# Duration: 30.684099674224854s

Now we can use lru_cache to optimize our code above and reduce 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 = time.time()fib_memoization(40)print(f'Duration: {time.time() - 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) Output:  0 [1, 2, 3] 4py, filename, *cmds = "python3.7 script.py -n 5 -l 15".split()print(py)print(filename)print(cmds) Output: python3.7
   script.py   ['-n', '5', '-l', '15']first, _, third, *_ = range(10)print(first, third) Output:  0 2

Data classes (3.7+)

Python3 provides the data class decorator to allow us to work better with data objects without implementing the init () and repr () methods. Suppose the following code:


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.4print(armor)# <__main__.Armor object at 0x7fc4800e2cf8>

The code that uses data class to achieve the above function reads as follows:


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

Implicit namespace packages (3.3+)

Normally, Python is reused by wrapping the code into a package (init. py implementation is added to the directory). The official example is as follows:


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

In Python2, as in the above directory structure, each directory must have init. py file, and other modules call python code in the directory once. In Python3, through Implicit Namespace Packages, __init__. py file is not used


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

Conclusion

Here due to time relations (really busy) only listed part of the new features of Python3, I hope you after reading this article, apply what you have learned, write a clearer and more intuitive code!


Related articles: