An overview of the

As Python2’s official maintenance period comes to an end, more Python projects are switching from Python2 to Python3. However, in the actual work, I found that many people are using Python2 thinking to write Python3 code, Python3 provides us with a lot of new, very convenient features, can help us write code quickly.

F – strings (+ 3.6)

In 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) Output: User Jane Doe has logged in and did an action buy.Copy the code

Python3 provides a more flexible and convenient way to format strings, called f-strings. The above code 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) : User Jane Doe has logged in and did an action buy.Copy the code

Pathlib (+ 3.4)

F-strings is too convenient, but Python provides a more convenient way to handle strings like file strings. Pathlib is a library provided by Python3 that handles file routing. Such as:

From pathlib import Path root = Path('post_sub_folder') print(root) Post_sub_folder path = root/ 'happy_user' print(path.resolve()) : /root/post_sub_folder/happy_userCopy the code

Type hinting (+ 3.5)

Static versus dynamic typing is a hot topic in software engineering, and everyone has different opinions. Python, as a dynamically typed language, also provides Type hinting in Python3, for example:

def sentence_has_animal(sentence: str) -> bool:
  return "animal" in sentence

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

The Enumerations (+ 3.4)

Python3 provides an Enum class that allows you to easily implement an Enum:

from enum import Enum, auto class Monster(Enum): ZOMBIE = auto() WARRIOR = auto() BEAR = auto() print(monster.zombie) Output: monster.zombieCopy the code

Python3’s Enum also supports comparison and iteration.

For monster in Monster: Print (monster) Output: Monster.zombie Monster.warrior Monster.bearCopy the code

Built – in LRU cache (+ 3.2)

Caching is a common technology in software today, and Python3 provides a lRU_cache decorator to make better use of caching. Here’s an example:

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.68409967422454sCopy the code

Now we can use lru_cache to optimize our above code 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 = time.time()
fib_memoization(40)
print(f'Duration: {time.time() - start}s')
# Duration: 6.866455078125e-05s
Copy the code

Extended iterable unpacking (+ 3.0)

Without further ado, let’s go to the code. The documentation is here

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, thirdCopy the code

Data classes (+ 3.7)

Python3 provides data Class decorators to allow us to work with data objects without having to implement init() and repr() methods. Assume 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 (5.2, "Common armor.", Power () # 10.4 print(armor) # <__main__.Armor object at 0x7fc4800e2cf8>Copy the code

Use data class to implement the above function code, write like this:

from dataclasses import dataclass @dataclass class Armor: armor: float description: str level: int = 1 def power(self) -> float: Return self. Armor * self. Level = armor (5.2, "Common armor.", Power () # 10.4 print(armor) # armor (description='Common armor.', level=2)Copy the code

Implicit namespace packages (+ 3.3)

Typically, Python recyls the code by packing it into a package (init.py in a directory). The official example is as follows:

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
Copy the code

In Python2, with the same directory structure as above, each directory must have an init.py file, which is called by other modules. In Python3, Implicit Namespace Packages are used instead of __init__.py

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
Copy the code

conclusion

This article has only listed some of the new Python3 features. I hope this article has shown you some of the new Python3 features that you didn’t know about before, and hopefully helped you write clearer and more intuitive code.