处理依赖项

开发 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 包

¡Vamos a practicar!

开发 Python 包

Preparing Video For Download...