当前位置: 首页 > news >正文

TypeError: cannot pickle ‘module‘ object

创建python对象时报错:
TypeError: cannot pickle 'module' object

原因:

很大可能是类成员错误的使用了第三方包(别名)等,具体排查方法可参考:

import redisimport pickle
from pprint import pformat as pfdef pickle_trick(obj, max_depth=10):output = {}if max_depth <= 0:return outputtry:pickle.dumps(obj)except (pickle.PicklingError, TypeError) as e:failing_children = []if hasattr(obj, "__dict__"):for k, v in obj.__dict__.items():result = pickle_trick(v, max_depth=max_depth - 1)if result:failing_children.append(result)output = {"fail": obj, "err": e, "depth": max_depth, "failing_children": failing_children}return outputif __name__ == "__main__":r = redis.Redis()print(pf(pickle_trick(r)))

另外附上说明: 

What can be pickled and unpickled?

The following types can be pickled:

  • None, True, and False

  • integers, floating point numbers, complex numbers

  • strings, bytes, bytearrays

  • tuples, lists, sets, and dictionaries containing only picklable objects

  • functions defined at the top level of a module (using def, not lambda)

  • built-in functions defined at the top level of a module

  • classes that are defined at the top level of a module

  • instances of such classes whose __dict__ or the result of calling __getstate__() is picklable (see section Pickling Class Instances for details).

As you can see, modules are not part of this list. Note, that this is also true when using deepcopy and not only for the pickle module, as stated in the documentation of deepcopy:

This module does not copy types like module, method, stack trace, stack frame, file, socket, window, array, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.

A possible workaround is using the @property decorator instead of an attribute. For example, this should work:

    import numpy as npimport pickleclass Foo():@propertydef module(self):return npfoo = Foo()with open('test.out', 'wb') as f:pickle.dump(foo, f)

参考资料:

Python: can't pickle module objects error - Stack Overflow 

http://www.lryc.cn/news/35174.html

相关文章:

  • [MySQL索引]3.索引的底层原理(二)
  • JavaScript混淆——逆向思维的艺术
  • 数据库管理-第六十期 监听(20230309)
  • 概率论与数理统计相关知识
  • SOC计算方法:卡尔曼滤波算法
  • 【C语言】自定义类型、枚举类型与宏定义
  • Java进阶(下篇2)
  • 03单链表
  • ESLint、Prettier插件的安装与使用
  • matlab在管理学中的应用简matlab基础【三】
  • NDK JNI 变声器实现
  • VMLogin防关联指纹浏览器的主帐号和子账号区别介绍
  • Apache DolphinScheduler GitHub Star 突破 10000!
  • 程序员中的女性力量——做不被定义的自己
  • pb中Datawindow中每页打印固定行
  • 华为OD机试 - 内存池(C 语言解题)【独家】
  • SaaS简介
  • unity 实现使用三张图片来表达车速,通过传值达到车速
  • 程序员看过都说好的资源网站,你值得拥有。
  • 【MySQL高级篇】第03章 用户与权限管理
  • MySQL的分库分表?通俗易懂
  • elasticsearch 查询语法
  • 深入剖析MVC模型与三层架构
  • 使用 Wall 搭建个人照片墙和视频墙
  • 03_Linux压缩解压,用户用户组,文件权限
  • 硬盘分区数据恢复?这些方法助您解忧
  • 高校竞赛信息管理系统
  • 还是要学好数学啊
  • ActiveMQ反序列化漏洞原理+复现
  • layui框架实战案例(19):layui-table模块表格综合应用(筛选查询、导入导出、群发短信、一键审核、照片展示、隐私加密)