为什么我必须在 pybson (=bson, GitHub:py-bson) 之后安装 pymongo 才能成功导入 pybson?

Why do I have to install pymongo after pybson (=bson, GitHub:py-bson) to get pybson imported successfully?

+++

编辑:将问题放到网上很长时间后,我注意到这是 Can't connect to MongoDB 2.0.5 database with pymongo 2.2 的衍生产品,它表示您必须在安装 pymongo 之前安装 bson。我在这里问的不是这个已知的解决方案,而是这个所需安装顺序的 原因。我添加了一个小东西,我将“bson”模块安装为“pybson”,这使得区分两个包的import bson名称冲突成为可能。

+++

我正在使用一种解决方法来避免 pymongo 的 bson 模块和 bson 的(GitHub 上的 py-bson)bson 模块的名称冲突:我将 bson 包安装为 pybson,请参阅 https://github.com/py-bson/bson/issues/70

根据 pip install of eve package installs bson and pymongo which breaks pymongo 的回答,我们得出了主要观点:

pymongo doesn't bring bson as a dependency, it just has its own bson implementation. The problem is pymongo installs its bson as a top-level directory in site-packages/ thus overwriting any existing bson there.

但这并不能解释为什么安装顺序 [1. bson, 2.pymongo] 解决了这个问题,相反你会期望它完全相反!

就我而言,我已经安装了一个新系统,使用anaconda 作为基础。我使用 pip install pybson 安装了 bson,它说:

Traceback (most recent call last):

File "", line 1, in import pybson # same as bson

File "C:\Users\Admin\anaconda3\lib\site-packages\pybson_init_.py", line 23, in from .objectid import ObjectId

File "C:\Users\Admin\anaconda3\lib\site-packages\pybson\objectid.py", line 30, in from bson.py3compat import PY3, bytes_from_hex, string_type, text_type

ModuleNotFoundError: No module named 'bson'

除了pybson 之外还安装了pymongo 之后,使用conda install pymongoimport pybson 语句起作用了。为什么?

问题的引用思路必须反过来:pip install bson after pip install pymongo 扰乱了 pymongo 的 bson 依赖性,因此 pymongo 的 bson 模块将不再工作。这可能不是因为 bson 覆盖了 pymongo 的 bson 依赖项,而是因为名称冲突:两个包使用相同的 bson 模块 'bson',这导致与 bson 覆盖 pymongo 的 bson 相同的效果。

很奇怪:如问题所述,除了 (py)bson 之外,您 安装 pymongo。这暗示 bson 在其自己的包中使用 pymongo 的 bson 依赖项。

因为在 pip install bson pip install pymongo 之后安装 bson 会干扰 pymongo 的 bson,参见 Can't connect to MongoDB 2.0.5 database with pymongo 2.2, we can assume that there is a name clash between the two bson modules which is dominated by the one that is installed as the last. It seems as if the (py)bson package needs a dominating pymongo bson dependency in addition to its own bson module, and (py)bson imports the pymongo dependency as import bson in its internal scripts, even though it has the bson module itself. I do not know whether the domination is caused by overwriting, or whether this is just a problem of the python environment. The former is more likely, since the order of installs (first pip install bson, afterwards pip install pymongo), becomes irrelevant as soon as you install bson with pip install pybson instead of pip install bson, see pip install of eve package installs bson and pymongo which breaks pymongo