iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 5
0

package and module

我們先從package開始吧。根據python文件的說法,package是一種帶有__path__屬性的module

A Python module which can contain submodules or recursively, subpackages.
Technically, a package is a Python module with an __path__ attribute.

根據這段描述帶出了兩個問題

  1. what is module
  2. what is __path__

先來看第一個問題,module是甚麼概念呢?

An object that serves as an organizational unit of Python code.
Modules have a namespace containing arbitrary Python objects.
Modules are loaded into Python by the process of importing.

namespace代表甚麼呢?

  • The place where a variable is stored
  • implemented as dictionaries
  • local, global and built-in namespaces as well as nested namespaces in objects (in methods)

再來看第二個問題

A package’s __path__ attribute is used during imports of its subpackages.
Within the import machinery, it functions much the same as sys.path, i.e. providing a list of locations to search for modules during import.

  1. 看起來module的本質上是一個物件。
  2. __path__的目的是存放import過程中會使用到的資料,與sys.path的功能性上類似

結論是一個包含__path__屬性的物件即為package

有兩種類型的package

  1. regular packages
    • traditional packages as they existed in Python 3.2 and earlier
    • typically implemented as a directory containing an __init__.py file.
    • When a regular package is imported, this __init__.py file is implicitly executed
  2. namespace packages

__init__.py in requests

因為requests目錄帶有__init__.py,所以可以將requests看成是一個regular package,當requests被其他module import時,預設會執行__init__.py

  1. 檢查urllib3和chardet相容性
    • urllib3 >= 1.21, <= 1.25
    • chardet >= 3.0.2, < 3.1.0
  2. 建議cryptography >= 1.3.4
  3. 從__version__載入相關資訊,例如title, description, version, author...
  4. 載入requests需要用到的物件或函式,使用了relative import
from . import utils
from . import packages
from .models import Request, Response, PreparedRequest
from .api import request, get, head, post, patch, put, delete, options
from .sessions import session, Session
from .status_codes import codes
from .exceptions import (
    RequestException, Timeout, URLRequired,
    TooManyRedirects, HTTPError, ConnectionError,
    FileModeWarning, ConnectTimeout, ReadTimeout
)

參考


上一篇
Day4-docs
下一篇
Day6-requests.get
系列文
Why it works: python requests and urllib330
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言