{"id":4461,"library":"bson","title":"BSON Codec for Python","description":"The `bson` library provides an independent codec for the BSON (Binary JSON) serialization format, without depending on MongoDB. It offers functions to efficiently serialize Python data structures into BSON bytes and deserialize BSON data back into Python objects. The current version is 0.5.10. Based on recent GitHub activity and a history of addressing issues, it appears to be actively maintained, though releases are not on a fixed schedule.","status":"active","version":"0.5.10","language":"en","source_language":"en","source_url":"https://github.com/py-bson/bson","tags":["bson","serialization","binary","codec","data-format"],"install":[{"cmd":"pip install bson","lang":"bash","label":"Install BSON library"}],"dependencies":[],"imports":[{"symbol":"dumps","correct":"import bson; bson.dumps(...)"},{"symbol":"loads","correct":"import bson; bson.loads(...)"},{"symbol":"ObjectId","correct":"from bson.objectid import ObjectId"},{"note":"Exceptions like InvalidBSON are in the bson.errors submodule, not directly under bson.","wrong":"import bson; bson.InvalidBSON","symbol":"InvalidBSON","correct":"from bson.errors import InvalidBSON"},{"note":"While 'BSON' is a class, module-level functions like dumps/loads are generally preferred for performance and simplicity. Direct import of the class is less common.","wrong":"from bson import BSON","symbol":"BSON","correct":"import bson; bson.BSON(...)"},{"note":"While PyMongo also has a json_util, this 'bson' library provides its own, though it's less commonly used than dumps/loads for raw BSON.","wrong":"from pymongo import json_util","symbol":"json_util","correct":"from bson import json_util"}],"quickstart":{"code":"import bson\nfrom bson.objectid import ObjectId\nfrom datetime import datetime, timezone\n\n# Create a Python dictionary with BSON-compatible types\ndata = {\n    \"message\": \"Hello BSON!\",\n    \"timestamp\": datetime.now(timezone.utc), # Use timezone-aware datetime for best practice\n    \"_id\": ObjectId(),\n    \"value\": 123.45,\n    \"tags\": [\"python\", \"bson\", \"example\"]\n}\n\n# Encode the dictionary to BSON bytes\nbson_data = bson.dumps(data)\nprint(f\"Encoded BSON (bytes): {bson_data}\")\n\n# Decode the BSON bytes back to a Python dictionary\ndecoded_data = bson.loads(bson_data)\nprint(f\"Decoded data: {decoded_data}\")\nprint(f\"Type of decoded_data: {type(decoded_data)}\")\nprint(f\"Type of _id in decoded_data: {type(decoded_data['_id'])}\")\n\n# Demonstrate handling InvalidBSON\ntry:\n    bson.loads(b\"invalid_bson_data\")\nexcept bson.errors.InvalidBSON as e:\n    print(f\"Caught expected error: {e}\")","lang":"python","description":"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."},"warnings":[{"fix":"If 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.","message":"Installing '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.","severity":"breaking","affected_versions":"All versions when co-installed with PyMongo"},{"fix":"For complex or custom Python objects, convert them into BSON-compatible Python types (like dictionaries, lists, basic types) before passing them to `bson.dumps()`.","message":"`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`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always 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.","message":"Decoding invalid, corrupted, or truncated BSON data will raise `bson.errors.InvalidBSON`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Prefer `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.","message":"When 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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"No direct fix needed, but be aware of minor version gaps in the historical release sequence.","message":"Release 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.","severity":"gotcha","affected_versions":"0.4.x"}],"env_vars":null,"last_verified":"2026-04-12T00:00:00.000Z","next_check":"2026-07-11T00:00:00.000Z"}