or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

custom-objects.mdindex.mdnetwork.mdobjectid.mdserialization.mdtypes.md
tile.json

tessl/pypi-bson

Independent BSON codec for Python that doesn't depend on MongoDB

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/bson@0.5.x

To install, run

npx @tessl/cli install tessl/pypi-bson@0.5.0

index.mddocs/

BSON

An independent BSON (Binary JSON) codec for Python that operates without dependency on MongoDB. It provides comprehensive serialization and deserialization capabilities for BSON format data, supporting standard Python data types and offering network socket extensions for atomic BSON object transmission.

Package Information

  • Package Name: bson
  • Language: Python
  • Installation: pip install bson
  • Dependencies: python-dateutil>=2.4.0, six>=1.9.0

Core Imports

import bson

For serialization and deserialization:

from bson import dumps, loads

For ObjectId support:

from bson import ObjectId

For network socket extensions:

from bson import patch_socket

Basic Usage

import bson

# Serialize Python dict to BSON
data = {"name": "Alice", "age": 30, "scores": [85, 92, 78]}
bson_bytes = bson.dumps(data)

# Deserialize BSON to Python dict
restored_data = bson.loads(bson_bytes)
print(restored_data)  # {'name': 'Alice', 'age': 30, 'scores': [85, 92, 78]}

# Working with ObjectIds
from bson import ObjectId
oid = ObjectId()
print(str(oid))  # e.g., '507f1f77bcf86cd799439011'

# Network socket usage
import socket
from bson import patch_socket

# Patch socket class to add BSON methods
bson.patch_socket()

# Now sockets can send/receive BSON objects
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# sock.sendobj({"message": "hello"})
# obj = sock.recvobj()

Architecture

The BSON package is structured around several key components:

  • Core Codec: Low-level BSON encoding/decoding functions with support for all BSON types
  • High-level API: Simple dumps() and loads() functions for easy serialization
  • ObjectId Implementation: MongoDB-compatible ObjectId class forked from PyMongo
  • Type System: Explicit integer type classes (Int32, Int64, UInt64) for precise control
  • Network Extensions: Socket patching for atomic BSON transmission over networks
  • Custom Object Support: BSONCoding abstract base class for custom serializable objects

Capabilities

Core Serialization

Primary BSON encoding and decoding functionality with support for all standard Python data types including dictionaries, lists, strings, numbers, dates, and binary data.

def dumps(obj, generator=None, on_unknown=None):
    """Convert Python object to BSON bytes"""

def loads(data):
    """Convert BSON bytes to Python object"""

Core Serialization

ObjectId Operations

MongoDB-compatible ObjectId implementation providing unique identifier generation, parsing, validation, and datetime-based creation for range queries.

class ObjectId:
    def __init__(self, oid=None): ...
    
    @classmethod
    def from_datetime(cls, generation_time): ...
    
    @classmethod
    def is_valid(cls, oid): ...
    
    @property
    def binary(self): ...
    
    @property
    def generation_time(self): ...

ObjectId Operations

Network Socket Extensions

Socket patching capabilities that add atomic BSON object transmission methods to Python socket objects, enabling seamless BSON communication over network connections.

def patch_socket():
    """Patch socket class with BSON methods"""

# Methods added to socket objects:
def recvbytes(self, bytes_needed, sock_buf=None): ...
def recvobj(self): ...  
def sendobj(self, obj): ...

Network Socket Extensions

Type System

Explicit integer type wrappers for precise control over BSON integer encoding, supporting 32-bit signed, 64-bit signed, and 64-bit unsigned integers.

class Int32:
    def __init__(self, value): ...
    def get_value(self): ...

class Int64:
    def __init__(self, value): ...
    def get_value(self): ...

class UInt64:
    def __init__(self, value): ...
    def get_value(self): ...

Type System

Custom Object Serialization

Framework for creating custom BSON-serializable objects through the BSONCoding abstract base class, with class registration and automatic serialization/deserialization.

class BSONCoding:
    def bson_encode(self): ...
    def bson_init(self, raw_values): ...

def import_class(cls): ...
def import_classes(*args): ...

Custom Object Serialization

Supported BSON Types

The package supports encoding and decoding of the following BSON types:

  • Doubles (float)
  • Strings (str/unicode)
  • Documents (dict)
  • Arrays (list/tuple)
  • Binary data (bytes)
  • ObjectIds
  • Booleans
  • UTC datetime
  • None/null values
  • 32-bit integers
  • 64-bit signed integers
  • 64-bit unsigned integers
  • Decimal (converted to double)
  • UUID (as binary subtype 4)
  • Custom BSONCoding objects

Unsupported BSON Types

The following BSON types are intentionally not supported for data exchange simplicity:

  • Undefined (0x06)
  • Regex (0x0b)
  • DBPointer (0x0c)
  • JavaScript code (0x0d)
  • Symbol (0x0e)
  • JavaScript with scope (0x0f)
  • MongoDB timestamp (0x11)