Description
Pycrates is a simple alternative to pickle for marshalling and unmarshalling of Python objects. Rather than trying to encode Python bytecode, Pycrates just handles serialization and deserialization of object state in a (hopefully) easy-to-use manner. To this end, the developer is expected to provide a manifest to guide the process. Pycrates makes no attempt to magically determine what should be serialized.
Features
- Easily add your own manifest fields to adapt data to serializable form and vice versa.
- Popular serialization methods like JSON and msgpack are auto-discovered and available.
- Non-invasive integration option.
Installation
pip install pycrates
Usage
1. Subclass Crate and attach a manifest.
from pycrates import Crate, Field
class BankAccount(Crate):
class __manifest__:
__method__ = 'json'
def __construct__(self, data):
# Pycrates doesn't know how to construct your class!
acct = BankAccount(data.account)
acct.balance = data.balance
return acct
account = Field()
balance = Field()
def __init__(self, account_number):
self.account = account_number
self.balance = 0.0
def withdraw(self, amount):
self.balance -= abs(amount)
def deposit(self, amount):
self.balance += abs(amount)
acct = BankAccount(12345)
acct.deposit(100)
acct.withdraw(33)
open('/tmp/bankaccount', 'wb+').write(acct.pack())
acct = BankAccount.unpack(open('/tmp/bankaccount', 'rb').read())
assert acct.account == 12345
assert acct.balance == (100 - 33)
2. Use cratify to couple a manifest with an existing class.
from pycrates import Field, cratify
class BankAccount(object):
def __init__(self, account_number):
self.account = account_number
self.balance = 0.0
def withdraw(self, amount):
self.balance -= abs(amount)
def deposit(self, amount):
self.balance += abs(amount)
class BankAccountManifest:
__method__ = 'json'
def __construct__(self, data):
acct = BankAccount(data.account)
acct.balance = data.balance
return acct
account = Field()
balance = Field()
acct = BankAccount(12345)
acct.deposit(100)
acct.withdraw(33)
BankAccountCrate = cratify(BankAccount, BankAccountManifest)
packed = BankAccountCrate.pack(acct)
acct = BankAccountCrate.unpack(packed)
Gotchas
- If you want to serialize fields that aren't readily serializable, you'll want to extend the pycrates.manifest.IField class.
- During reconstruction/unmarshalling, Pycrates patches data after initialization of the target class. This means that if your object constructor has side effects, pycrates may leave your object in a bad state. Beware!
License
See LICENSE.txt for license details.