Things you are probably not using in python 3 but should -渣渣翻譯- python3 好在哪裏

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

 

Many people started switching their Python versions from 2 to 3 as a result of Python EOL. Unfortunately, most Python 3 I find still looks like Python 2, but with parentheses (even I am guilty of that in my code examples in previous posts – Introduction to web scraping with Python). Below, I show some examples of exciting features you can only use in Python 3 in the hopes that it will make solving your problems with Python easier.python

All the examples are written in Python 3.7 and each feature contains the minimum required version of Python for that feature.git

parentheses :n. 圓括號,插入語,插曲
guilty :adj. 有罪的;內疚的

 

由於python2終將中止維護,不少人已經在將python的版本由2轉向3。可是我發現不少的python3的代碼風格依然是python2,只是帶上了括號(我很內疚,由於在我以前的一片文章中也犯過這樣的錯誤-介紹使用python爬取web頁面)。下面,我會展現一些只在python3中才有的特性的例子,但願能夠輕鬆解決你在使用python的過程當中遇到的問題。github

全部的例子都是使用python3.7編寫,並且每一種都包含該特性的python最低需求的版本。web

f-strings (3.6+)

It is difficult to do anything without strings in any programming language and in order to stay sane, you want to have a structured way to work with strings. Most people using Python prefer using the format method.算法

sane :adj. 心智健全的; 神志正常的
structure :n. 結構, 構造,有結構的事物; 複雜的總體; 建築物 vt. 組織; 安排; 構造; 制定

字符串方法f-strings(3.6+)編程

在任何編程語言中,若是沒有字符串功能都會很困難,爲了可以保持理智,你會想要一種結構化的方法來處理字符串。不少人在使用python的時候更願意用fomat方法api

 

    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.

 

Alongside of format, Python 3 offers a flexible way to do string interpolation via f-strings. The same code as above using f-strings looks like this:緩存

Alongside :    adv. 靠着邊, 沿着邊     prep. (表示位置)在…旁邊; 沿着…的邊; 與…並排靠攏着     (表示比較)與…放在一塊兒比較     (表示伴隨)與…一塊兒, 與…一道
flexible :adj. 靈活的;柔韌的;易彎曲的
interpolation :篡改,填寫,插補

 

相比於format,python3經過f-strings提供了一種更靈活的方式操做字符串。相同的代碼,在f-strings下以下所示:app

    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 are amazing, but some strings like file paths have their own libraries which make their manipulation even easier. Python 3 offers pathlib as a convenient abstraction for working with file paths. If you are not sure why you should be using pathlib, try reading this excellent post – Why you should be using pathlib – by Trey Hunner.

manipulation :    n. (熟練的)操做;操縱;控制     (對帳目等的)僞造,篡改
convenient :adj. 方便的, 便利的, 合適的
abstraction :    n. 抽象,抽取 抽象化;抽象過程 抽象概念;抽象名稱 抽象性,抽象的特徵 出神;心不在焉 不切實際的想法,空想;幻想的事物 (藝術上的)抽象主義 <邏>抽象,抽離;抽離運符 <婉>偷竊
excellent :adj. 優秀的, 卓越的, 傑出的

 

f-string已經很棒了,可是有一些字符串,像文件路徑,有專用的函數庫用來處理會更方變和簡單,python3提供了pathlib做爲操做文件路徑的一個很方便的抽象方法,若是你還不肯定爲何要使用pathlib,請試一下讀一讀Trey Hunner的這篇文章-Why you should be using pathlib。

    from pathlib import Path
    root = Path('post_sub_folder')
    print(root)
    # post_sub_folder
    path = root / 'happy_user'
    # Make the path absolute
    print(path.resolve())
    # /home/weenkus/Workspace/Projects/DataWhatNow-Codes/how_your_python3_should_look_like/post_sub_folder/happy_user

Type hinting (3.5+)

Static vs dynamic typing is a spicy topic in software engineering and almost everyone has an opinion on it. I will let the reader decide when they should write types, but I think you should at least know that Python 3 supports type hints.

spicy :adj. 辛辣的;香的,多香料的;下流的
opinion :意見
hint :    n. 暗示;線索     vt. 暗示;示意     vi. 示意

 

靜態和動態類型一直是軟件工程師爭論的熱門話題,全部的人都有本身的主見,我會讓讀者本身決定是否是要標明類型,可是我認爲你至少應該知道python3支持類型提示。

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

 

Enumerations (3.4+)

Python 3 supports an easy way to write enumerations through the Enum class. Enums are a convenient way to encapsulate lists of constants so they are not randomly located all over your code without much structure.

enumerations :應該是一種枚舉類型
encapsulate :    vt. 裝入膠囊     總結;扼要歸納;囊括     adj. 有(膠)囊包着的
constant :    adj. 始終如一的, 恆久不變的     不斷的, 連續發生的     忠實的, 忠誠的

 

python3能夠經過Enum這個類簡單的寫出一個enumerations。Enums是一種用來封裝列表的簡單方法,它不會隨機的分佈在你的代碼中,不會有太多的結構。

https://www.cnblogs.com/bdhk/p/7506691.html對Enum和auto有比較詳細的解釋

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

An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.

https://docs.python.org/3/library/enum.html
 
symbolic :adj. 象徵的, 象徵性的

 

枚舉是一組集合,綁定了惟一常量值的變量名(成員)。 在枚舉中,能夠經過標識來比較成員,而且枚舉自己能夠迭代。
    for monster in Monster:
        print(monster)
    # Monster.ZOMBIE
    # Monster.WARRIOR
    # Monster.BEAR

 

Built-in LRU cache (3.2+)

Caches are present in almost any horizontal slice of the software and hardware we use today. Python 3 makes using them very simple by exposing an LRU (Least Recently Used) cache as a decorator called lru_cache.

Below is a simple Fibonacci function that we know will benefit from caching because it does the same work multiple times through a recursion.

Built-in :內置
LRU :內存管理的一種頁面置換算法,對於在內存中但又不用的數據塊(內存塊)叫作LRU,Least recently used,最近最少使用
present :    vt. 呈現;介紹;提出;贈送     vi. 舉槍瞄準     adj. 出席的;如今的     n. 如今;禮物;瞄準
horizontal :adj. 水平的, 與地平線平行的
exposing :
n. 遺棄;露體;陳列v. 展覽;揭露;遭遇(expose的ing形式)
recursion :遞歸式

 

現在,高速緩存已經存在於咱們使用的硬件和軟件的各個層面。Python3能夠簡單的使用他們,經過調用裝飾器-lru_cache來展現一個LRU cache。(以爲翻譯的不給力,尤爲是exposing)

下面是一個簡單的Fibonacci function(斐波那契函數),咱們知道它將從緩存中受益,由於它經過遞歸屢次執行相同的工做。

    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 the lru_cache to optimize it (this optimization technique is called memoization). The execution time goes down from seconds to nanoseconds.

optimize :vt. 使最優化,使完善;vi. 優化;持樂觀態度
memoization :記憶化

 

如今,咱們可使用lru_cache來優化它(這種優化技術稱爲memoization)。執行時間從幾秒到減小到幾納秒。

推薦閱讀:http://www.javashuo.com/article/p-qkmfygrv-ka.html

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

對可迭代對象的擴展解包

I will let the code speak here (docs).

我將讓代碼本身說話。

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

Python 3 introduces data classes which do not have many restrictions and can be used to reduce boilerplate code because the decorator auto-generates special methods, such as __init__() and __repr()__. From the official proposal, they are described as 「mutable named tuples with defaults」.

introduce :vt. 介紹, 引見 提出, 提出供討論 引進, 採用 將…放[插]入
restrictions :約束,限制
boilerplate :樣板文件
generates :vt. 使造成;生殖;發生
proposal :提議,建議,求婚
mutable :adj. 易變的,性情不定的

 

Python 3引入了數據類,這些數據類沒有太多限制,而且能夠用來減小樣板代碼,由於裝飾器會自動生成特殊的方法,好比__init__()和__repr__()。根據官方建議,它們被描述爲具備默認值的可變命名元組。

    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>

The same implementation of Armor using data classes.

implementation :n. 貫徹,執行

 

使用data classes 執行相同的Armor

    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)   

注:最後打印的對象的形式,是我讀到這裏以爲最棒的東西,再也不像以前的,只是一個關於對象的歸屬信息和一個內存編碼的東西。這就是我須要的。不用再頻繁的使用__dict__

Implicit namespace packages (3.3+)

隱含名稱空間的包結構

One way to structure Python code is in packages (folders with an __init__.py file). The example below is given by the official Python documentation.

Implicit :adj. 暗示的;盲從的;含蓄的
structure :n. 結構, 構造 有結構的事物; 複雜的總體; 建築物 vt. 組織; 安排; 構造; 制定
folders :n. 文件夾,方法;摺頁,檔案夾

 

一種構造python代碼目錄結構的方式是用包(在文件夾中放一個__init__.py文件)。下面是Python官方文檔給出的例子

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

In Python 2, every folder above had to have an __init__.py file which turned that folder into a Python package. In Python 3, with the introduction of Implicit Namespace Packages, these files are no longer required.

在python2中,每個文件夾下面都有一個__init__.py文件,做爲將文件夾轉換成一個包文件。在python3中,隨着Implicit Namespace Packages的引入,再也不須要這些文件了。

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

 

EDIT: as some people have said, this is not as simple as I pointed it out in this section, from the official PEP 420 Specification__init__.py is still required for regular packages, dropping it from the folder structure will turn it into a native namespace package which comes with additional restrictions, the official docs on native namespace packages show a great example of this, as well as naming all the restrictions.

regular :    adj. 整齊的;按期的;有規律的;合格的     n. 正式隊員;常客;中堅分子     adv. 常常地;按期地
additional :adj. 增長的, 額外的, 另外的

 

編者:正若有些人說的那樣,並不像本章節描述的那樣簡單,官方文檔PEP 420 Specification指出- 常規包仍然須要__init__.py ,將它從結構中刪除後,會把包變成一個被限制的native namespace package(本地命名空間),官方文檔中對native namespace package(本地命名空間)列舉了相關例子,以及對命名的全部限制。

Closing note

Like almost any list on the internet, this one is not complete. I hope this post has shown you at least one Python 3 functionality you did not know existed before, and that it will help you write cleaner and more intuitive code. As always, all the code can be found on GitHub.

intuitive :adj. 有直覺力的;憑直覺獲知的

 

就像互聯網上的全部列表同樣,這個列表並不完整。 我但願這篇文章向您展現了至少一個你之前不知道的Python 3功能,而且它將幫助您編寫更清晰,更直觀的代碼。 與往常同樣,全部代碼均可以在GitHub上找到。

相關文章
相關標籤/搜索