處理相依套件

開發 Python 套件

James Fulton

Climate informatics researcher

什麼是相依套件?

  • 你在套件中匯入的其他套件
  • mymodule.py 中:
# 這些匯入的套件是相依套件
import numpy as np
import pandas as pd
...
開發 Python 套件

在 setup.py 加入相依套件

from setuptools import setup, find_packages

setup(
    ...
    install_requires=['pandas', 'scipy', 'matplotlib'],
)
開發 Python 套件

控管相依版本

from setuptools import setup, find_packages

setup(
    ...
    install_requires=[

'pandas>=1.0',
'scipy==1.1',
'matplotlib>=2.2.1,<3'
], )
開發 Python 套件

控管相依版本

from setuptools import setup, find_packages

setup(
    ...
    install_requires=[

'pandas>=1.0', # good 'scipy==1.1', # bad 'matplotlib>=2.2.1,<3' # good ], )
  • 盡量允許更多版本
  • 移除未使用的相依套件
開發 Python 套件

Python 版本

from setuptools import setup, find_packages

setup(
    ...
    python_requires='>=2.7, !=3.0.*, !=3.1.*',
)
開發 Python 套件

選擇相依與套件版本

NumPy 發行說明範例。

開發 Python 套件

建立開發者環境

pip freeze
alabaster==0.7.12
appdirs==1.4.4
argh==0.26.2
...
wrapt==1.11.2
yapf==0.29.0
zipp==3.1.0
開發 Python 套件

建立開發者環境

將套件需求儲存到檔案

pip freeze > requirements.txt

從檔案安裝需求

pip install -r requirements.txt
mysklearn/
|-- mysklearn
|   |-- __init__.py
|   |-- preprocessing
|   |   |-- __init__.py
|   |   |-- normalize.py
|   |   |-- standardize.py
|   |-- regression
|   |   |-- __init__.py
|   |   |-- regression.py
|   |-- utils.py
|-- setup.py
|-- requirements.txt   <-- 開發者環境
開發 Python 套件

一起來練習吧!

開發 Python 套件

Preparing Video For Download...