Install & Compatibility
Where this runs
tested against v0.5.10 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.054s · 20.1MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 2.5s · import 0.046s · 21MB
18MB installed
● package 18MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
dumps
✓ from bson import dumps
✗ import bson; bson.dumps(...)
This example demonstrates how to encode a Python dictionary containing common BSON types (string, datetime, ObjectId, float, list) into BSON bytes using `bson.dumps()`, and then decode it back into a Python dictionary using `bson.loads()`. It also shows how to catch `bson.errors.InvalidBSON` for corrupted or invalid BSON data.
import bson
from bson.objectid import ObjectId
from datetime import datetime, timezone
# Create a Python dictionary with BSON-compatible types
data = {
"message": "Hello BSON!",
"timestamp": datetime.now(timezone.utc), # Use timezone-aware datetime for best practice
"_id": ObjectId(),
"value": 123.45,
"tags": ["python", "bson", "example"]
}
# Encode the dictionary to BSON bytes
bson_data = bson.dumps(data)
print(f"Encoded BSON (bytes): {bson_data}")
# Decode the BSON bytes back to a Python dictionary
decoded_data = bson.loads(bson_data)
print(f"Decoded data: {decoded_data}")
print(f"Type of decoded_data: {type(decoded_data)}")
print(f"Type of _id in decoded_data: {type(decoded_data['_id'])}")
# Demonstrate handling InvalidBSON
try:
bson.loads(b"invalid_bson_data")
except bson.errors.InvalidBSON as e:
print(f"Caught expected error: {e}")
Debug
Known issues
breakingInstalling 'bson' from PyPI can cause conflicts and `ImportError` when PyMongo is also installed. PyMongo ships with its own `bson` package, and the independent 'bson' package from PyPI is incompatible.fixIf using PyMongo, rely on its internal `bson` module (`from bson import ObjectId` will import PyMongo's version). If you need the independent 'bson' library, ensure it's installed in an isolated environment or consider using `pip install py-bson` if a renamed package becomes available to avoid the name clash. If you encounter issues, `pip uninstall bson pymongo` then `pip install pymongo` (or `pip install bson` if you *only* need the independent bson) is often required.
affects: All versions when co-installed with PyMongo
gotcha`bson.dumps()` only supports BSON-defined data types. Attempting to encode custom Python objects (e.g., instances of custom classes) directly will raise a `TypeError`.fixFor complex or custom Python objects, convert them into BSON-compatible Python types (like dictionaries, lists, basic types) before passing them to `bson.dumps()`.
affects: All versions
gotchaDecoding invalid, corrupted, or truncated BSON data will raise `bson.errors.InvalidBSON`.fixAlways wrap `bson.loads()` calls in a `try...except bson.errors.InvalidBSON` block to gracefully handle malformed input. Ensure BSON data is complete and correctly formatted before decoding.
affects: All versions
gotchaWhen encoding `datetime` objects, using `datetime.now()` without specifying a timezone can lead to ambiguity. It's best practice to use `datetime.utcnow()` for naive UTC timestamps or timezone-aware `datetime` objects.fixPrefer `datetime.now(timezone.utc)` or `datetime.utcnow()` when creating `datetime` objects to be encoded into BSON to avoid timezone-related issues during serialization and deserialization.
affects: All versions
gotchaRelease 0.4.5 was skipped due to a 'version issue with pypi'. While not directly impacting users, it indicates potential historical inconsistencies in the release process.fixNo direct fix needed, but be aware of minor version gaps in the historical release sequence.
affects: 0.4.x
Upgrade
Version history
0.5.10latest on PyPI · released May 26, 2020
Audit
Dependencies
No dependency data recorded yet.