Python weekly -- Things you’re probably not using in Python 3 – but should

Python weekly  -- Things you’re probably not using in Python 3 – but should

1. f-strings (3.6+)

相对format方法更加灵活的 f-strings

user = 'hello'
age = 008
say_something = f'user {user} has been lived {age} years'
print(say_something)

2. Pathlib (3.4+)

对文件路径更方便的抽象

# C:\lizude\temp\github\math\math_project\math_project\async_decorator.py
from pathlib import Path
root = Path('math_project')
path = root / 'async_decorator'   # 绝对路径
print(path.resolve())

输出:C:\lizude\temp\github\math\math_project\math_project\async_decorator

3. Type hinting (3.5+)

类型指定,包括参数和函数return 结果

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


sentence_has_animal('donald had a farm without animals')

4. Enumerations (3.4+)

通过 Enum 类可以更方便的写枚举

from enum import Enum, auto
class Monster(Enum):
    ZOMBIE = auto()
    WARRIOR = auto()
    BEAR = auto()
    
print(Monster.ZOMBIE)
# Monster.ZOMBIE
for monster in Monster:
    print(monster)
# Monster.ZOMBIE
# Monster.WARRIOR
# Monster.BEAR

5. Built-in LRU cache (3.2+)

缓存目前几乎是软件和硬件的水平切片
Python 3 makes using them very simple by exposing an LRU (Least Recently Used) cache as a decorator called lru_cache.

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
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

6. Extended iterable unpacking (3.0+)

解包的扩展

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(8)
print(first, third)
# 0, 2

7. Data classes (3.7+)

数据类 , 官方描述为可改变的有默认值的命名元组

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>
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(6, 'common armor.', 2)
armor.power()
# 12
print(armor)
# Armor(armor=6, description='common armor.', level=2)

8. Implicit namespace packages (3.3+)

盲目的包的命名空间
定义一个包的方法是 init.py文件
在现在不用每个子文件夹都要 init.py文件

# 每个都有__init__.py
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
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
              ...

原文:https://datawhatnow.com/things-you-are-probably-not-using-in-python-3-but-should/

上一篇:vue多个数据不一样的表格导出到同一张excel里面


下一篇:面向对象基础之封装