[Python] Why do I have to install pymongo after pybson (=bson, GitHub:py-bson) to get pybson...

Discussão em 'Python' iniciado por Stack, Setembro 2, 2025.

  1. Stack

    Stack Membro Participativo

    +++

    EDIT: Long time after putting the question online I noticed that this is a spin-off of Can't connect to MongoDB 2.0.5 database with pymongo 2.2 which says that you have to install bson before you install pymongo. I am asking here not for this already known solution, but for the reason of this needed install order. And I add a small thing, I am installing "bson" module as "pybson", which makes it possible to distinguish the import bson name clash of the two packages.

    +++

    I am using a workaround to avoid the name clash of pymongo's bson module and bson's (py-bson on GitHub) bson module: I am installing bson package as pybson, see https://github.com/py-bson/bson/issues/70.

    From the answer at pip install of eve package installs bson and pymongo which breaks pymongo, we get the main idea:


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

    But this does not explain why the install order [1. bson, 2. pymongo] solves the issue, instead you would expect it to be exactly the other way round!

    In my case, I have installed a new system, using anaconda as the base. I had installed bson using pip install pybson, and it said:


    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'
    ​

    After installing pymongo in addition to pybson, using conda install pymongo, the import pybson statement worked. Why?

    Continue reading...

Compartilhe esta Página