Effective Python 读书笔记: 第44条: 用copyreg实现可靠的pickle操作

# -*- encoding: utf-8 -*-

import copy_reg
import pickle

'''
第44条: 用copyreg实现可靠的pickle操作

关键:
1 pickle模块
作用: 能够将Python对象序列转化为字节流,并反序列化为Python对象
    开发者可以在自己控制的各个程序之间传递python对象
定义:
pickle.dump(obj, file, protocol=None):
obj: 待序列化的对象
file: 存储序列化对象的文件

pickle.load(file)
file: 存储序列化对象的文件
用法:
    state = GameState()
    state.level += 1
    state.lives -= 1
    statePath = "/tmp/gameState.bin"
    with open(statePath, "wb") as f:
        pickle.dump(state, f)
    with open(statePath, 'rb') as f:
        stateAfter = pickle.load(f)
        
2 copyreg
定义: 注册函数,python对象的序列化由这些函数负责
作用:
1) 为缺失的属性提供默认值
2) 用版本号来管理类
在copy_reg注册的函数中添加表示版本号的参数,
根据版本号,在关键字参数中根据版本号参数做相应的处理
3) 固定的引入路径
当类的名称改变后,元有数据无法执行反序列化操作
解决方法: 给函数指定固定标识符,令它采用这个标识符对数据进行
unpickle操作

3 总结
pickle可以对python对象进行序列化和反序列化,
结合copy_reg和picke使用,为旧数据添加缺失的属性值,进行类版本管理,
给序列化数据提供固定引入路径

参考:
Effectiv Python 编写高质量Python代码的59个有效方法
'''

class GameState(object):
    def __init__(self, level=0, lives=4, points=0, name='chao'):
        self.level = level
        self.lives = lives
        self.points = points
        # self.name = name


def pickleGameState(gameState):
    kwargs = gameState.__dict__
    kwargs['version'] = 2
    return unpickleGameState, (kwargs,)


def unpickleGameState(kwargs):
    version = kwargs.pop('version', 1)
    if 1 == version:
        kwargs.pop('name')
    return GameState(**kwargs)


def processPickle():
    state = GameState()
    state.level += 1
    state.lives -= 1
    statePath = "/tmp/gameState.bin"
    with open(statePath, "wb") as f:
        pickle.dump(state, f)
    with open(statePath, 'rb') as f:
        stateAfter = pickle.load(f)
    print stateAfter.__dict__
    print type(stateAfter)


def processCopyregPickle():
    copy_reg.pickle(GameState, pickleGameState)
    state = GameState()
    state.points += 1000
    serialized = pickle.dumps(state)
    stateAfter = pickle.loads(serialized)
    print stateAfter.__dict__


def process():
    processPickle()
    processCopyregPickle()


if __name__ == "__main__":
    process() 

猜你喜欢

转载自blog.csdn.net/qingyuanluofeng/article/details/88987585