_dill.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
  4. # Copyright (c) 2008-2015 California Institute of Technology.
  5. # Copyright (c) 2016-2023 The Uncertainty Quantification Foundation.
  6. # License: 3-clause BSD. The full license text is available at:
  7. # - https://github.com/uqfoundation/dill/blob/master/LICENSE
  8. """
  9. dill: a utility for serialization of python objects
  10. The primary functions in `dill` are :func:`dump` and
  11. :func:`dumps` for serialization ("pickling") to a
  12. file or to a string, respectively, and :func:`load`
  13. and :func:`loads` for deserialization ("unpickling"),
  14. similarly, from a file or from a string. Other notable
  15. functions are :func:`~dill.dump_module` and
  16. :func:`~dill.load_module`, which are used to save and
  17. restore module objects, including an intepreter session.
  18. Based on code written by Oren Tirosh and Armin Ronacher.
  19. Extended to a (near) full set of the builtin types (in types module),
  20. and coded to the pickle interface, by <mmckerns@caltech.edu>.
  21. Initial port to python3 by Jonathan Dobson, continued by mmckerns.
  22. Tested against "all" python types (Std. Lib. CH 1-15 @ 2.7) by mmckerns.
  23. Tested against CH16+ Std. Lib. ... TBD.
  24. """
  25. from __future__ import annotations
  26. __all__ = [
  27. 'dump','dumps','load','loads','copy',
  28. 'Pickler','Unpickler','register','pickle','pickles','check',
  29. 'DEFAULT_PROTOCOL','HIGHEST_PROTOCOL','HANDLE_FMODE','CONTENTS_FMODE','FILE_FMODE',
  30. 'PickleError','PickleWarning','PicklingError','PicklingWarning','UnpicklingError',
  31. 'UnpicklingWarning',
  32. ]
  33. __module__ = 'dill'
  34. import warnings
  35. from .logger import adapter as logger
  36. from .logger import trace as _trace
  37. log = logger # backward compatibility (see issue #582)
  38. import os
  39. import sys
  40. diff = None
  41. _use_diff = False
  42. OLD38 = (sys.hexversion < 0x3080000)
  43. OLD39 = (sys.hexversion < 0x3090000)
  44. OLD310 = (sys.hexversion < 0x30a0000)
  45. OLD312a7 = (sys.hexversion < 0x30c00a7)
  46. #XXX: get types from .objtypes ?
  47. import builtins as __builtin__
  48. from pickle import _Pickler as StockPickler, Unpickler as StockUnpickler
  49. from pickle import GLOBAL, POP
  50. from _thread import LockType
  51. from _thread import RLock as RLockType
  52. #from io import IOBase
  53. from types import CodeType, FunctionType, MethodType, GeneratorType, \
  54. TracebackType, FrameType, ModuleType, BuiltinMethodType
  55. BufferType = memoryview #XXX: unregistered
  56. ClassType = type # no 'old-style' classes
  57. EllipsisType = type(Ellipsis)
  58. #FileType = IOBase
  59. NotImplementedType = type(NotImplemented)
  60. SliceType = slice
  61. TypeType = type # 'new-style' classes #XXX: unregistered
  62. XRangeType = range
  63. from types import MappingProxyType as DictProxyType, new_class
  64. from pickle import DEFAULT_PROTOCOL, HIGHEST_PROTOCOL, PickleError, PicklingError, UnpicklingError
  65. import __main__ as _main_module
  66. import marshal
  67. import gc
  68. # import zlib
  69. import abc
  70. import dataclasses
  71. from weakref import ReferenceType, ProxyType, CallableProxyType
  72. from collections import OrderedDict
  73. from enum import Enum, EnumMeta
  74. from functools import partial
  75. from operator import itemgetter, attrgetter
  76. GENERATOR_FAIL = False
  77. import importlib.machinery
  78. EXTENSION_SUFFIXES = tuple(importlib.machinery.EXTENSION_SUFFIXES)
  79. try:
  80. import ctypes
  81. HAS_CTYPES = True
  82. # if using `pypy`, pythonapi is not found
  83. IS_PYPY = not hasattr(ctypes, 'pythonapi')
  84. except ImportError:
  85. HAS_CTYPES = False
  86. IS_PYPY = False
  87. NumpyUfuncType = None
  88. NumpyDType = None
  89. NumpyArrayType = None
  90. try:
  91. if not importlib.machinery.PathFinder().find_spec('numpy'):
  92. raise ImportError("No module named 'numpy'")
  93. NumpyUfuncType = True
  94. NumpyDType = True
  95. NumpyArrayType = True
  96. except ImportError:
  97. pass
  98. def __hook__():
  99. global NumpyArrayType, NumpyDType, NumpyUfuncType
  100. from numpy import ufunc as NumpyUfuncType
  101. from numpy import ndarray as NumpyArrayType
  102. from numpy import dtype as NumpyDType
  103. return True
  104. if NumpyArrayType: # then has numpy
  105. def ndarraysubclassinstance(obj_type):
  106. if all((c.__module__, c.__name__) != ('numpy', 'ndarray') for c in obj_type.__mro__):
  107. return False
  108. # anything below here is a numpy array (or subclass) instance
  109. __hook__() # import numpy (so the following works!!!)
  110. # verify that __reduce__ has not been overridden
  111. if obj_type.__reduce_ex__ is not NumpyArrayType.__reduce_ex__ \
  112. or obj_type.__reduce__ is not NumpyArrayType.__reduce__:
  113. return False
  114. return True
  115. def numpyufunc(obj_type):
  116. return any((c.__module__, c.__name__) == ('numpy', 'ufunc') for c in obj_type.__mro__)
  117. def numpydtype(obj_type):
  118. if all((c.__module__, c.__name__) != ('numpy', 'dtype') for c in obj_type.__mro__):
  119. return False
  120. # anything below here is a numpy dtype
  121. __hook__() # import numpy (so the following works!!!)
  122. return obj_type is type(NumpyDType) # handles subclasses
  123. else:
  124. def ndarraysubclassinstance(obj): return False
  125. def numpyufunc(obj): return False
  126. def numpydtype(obj): return False
  127. from types import GetSetDescriptorType, ClassMethodDescriptorType, \
  128. WrapperDescriptorType, MethodDescriptorType, MemberDescriptorType, \
  129. MethodWrapperType #XXX: unused
  130. # make sure to add these 'hand-built' types to _typemap
  131. CellType = type((lambda x: lambda y: x)(0).__closure__[0])
  132. PartialType = type(partial(int, base=2))
  133. SuperType = type(super(Exception, TypeError()))
  134. ItemGetterType = type(itemgetter(0))
  135. AttrGetterType = type(attrgetter('__repr__'))
  136. try:
  137. from functools import _lru_cache_wrapper as LRUCacheType
  138. except ImportError:
  139. LRUCacheType = None
  140. if not isinstance(LRUCacheType, type):
  141. LRUCacheType = None
  142. def get_file_type(*args, **kwargs):
  143. open = kwargs.pop("open", __builtin__.open)
  144. f = open(os.devnull, *args, **kwargs)
  145. t = type(f)
  146. f.close()
  147. return t
  148. FileType = get_file_type('rb', buffering=0)
  149. TextWrapperType = get_file_type('r', buffering=-1)
  150. BufferedRandomType = get_file_type('r+b', buffering=-1)
  151. BufferedReaderType = get_file_type('rb', buffering=-1)
  152. BufferedWriterType = get_file_type('wb', buffering=-1)
  153. try:
  154. from _pyio import open as _open
  155. PyTextWrapperType = get_file_type('r', buffering=-1, open=_open)
  156. PyBufferedRandomType = get_file_type('r+b', buffering=-1, open=_open)
  157. PyBufferedReaderType = get_file_type('rb', buffering=-1, open=_open)
  158. PyBufferedWriterType = get_file_type('wb', buffering=-1, open=_open)
  159. except ImportError:
  160. PyTextWrapperType = PyBufferedRandomType = PyBufferedReaderType = PyBufferedWriterType = None
  161. from io import BytesIO as StringIO
  162. InputType = OutputType = None
  163. from socket import socket as SocketType
  164. #FIXME: additionally calls ForkingPickler.register several times
  165. from multiprocessing.reduction import _reduce_socket as reduce_socket
  166. try: #pragma: no cover
  167. IS_IPYTHON = __IPYTHON__ # is True
  168. ExitType = None # IPython.core.autocall.ExitAutocall
  169. IPYTHON_SINGLETONS = ('exit', 'quit', 'get_ipython')
  170. except NameError:
  171. IS_IPYTHON = False
  172. try: ExitType = type(exit) # apparently 'exit' can be removed
  173. except NameError: ExitType = None
  174. IPYTHON_SINGLETONS = ()
  175. import inspect
  176. import typing
  177. ### Shims for different versions of Python and dill
  178. class Sentinel(object):
  179. """
  180. Create a unique sentinel object that is pickled as a constant.
  181. """
  182. def __init__(self, name, module_name=None):
  183. self.name = name
  184. if module_name is None:
  185. # Use the calling frame's module
  186. self.__module__ = inspect.currentframe().f_back.f_globals['__name__']
  187. else:
  188. self.__module__ = module_name # pragma: no cover
  189. def __repr__(self):
  190. return self.__module__ + '.' + self.name # pragma: no cover
  191. def __copy__(self):
  192. return self # pragma: no cover
  193. def __deepcopy__(self, memo):
  194. return self # pragma: no cover
  195. def __reduce__(self):
  196. return self.name
  197. def __reduce_ex__(self, protocol):
  198. return self.name
  199. from . import _shims
  200. from ._shims import Reduce, Getattr
  201. ### File modes
  202. #: Pickles the file handle, preserving mode. The position of the unpickled
  203. #: object is as for a new file handle.
  204. HANDLE_FMODE = 0
  205. #: Pickles the file contents, creating a new file if on load the file does
  206. #: not exist. The position = min(pickled position, EOF) and mode is chosen
  207. #: as such that "best" preserves behavior of the original file.
  208. CONTENTS_FMODE = 1
  209. #: Pickles the entire file (handle and contents), preserving mode and position.
  210. FILE_FMODE = 2
  211. ### Shorthands (modified from python2.5/lib/pickle.py)
  212. def copy(obj, *args, **kwds):
  213. """
  214. Use pickling to 'copy' an object (i.e. `loads(dumps(obj))`).
  215. See :func:`dumps` and :func:`loads` for keyword arguments.
  216. """
  217. ignore = kwds.pop('ignore', Unpickler.settings['ignore'])
  218. return loads(dumps(obj, *args, **kwds), ignore=ignore)
  219. def dump(obj, file, protocol=None, byref=None, fmode=None, recurse=None, **kwds):#, strictio=None):
  220. """
  221. Pickle an object to a file.
  222. See :func:`dumps` for keyword arguments.
  223. """
  224. from .settings import settings
  225. protocol = settings['protocol'] if protocol is None else int(protocol)
  226. _kwds = kwds.copy()
  227. _kwds.update(dict(byref=byref, fmode=fmode, recurse=recurse))
  228. Pickler(file, protocol, **_kwds).dump(obj)
  229. return
  230. def dumps(obj, protocol=None, byref=None, fmode=None, recurse=None, **kwds):#, strictio=None):
  231. """
  232. Pickle an object to a string.
  233. *protocol* is the pickler protocol, as defined for Python *pickle*.
  234. If *byref=True*, then dill behaves a lot more like pickle as certain
  235. objects (like modules) are pickled by reference as opposed to attempting
  236. to pickle the object itself.
  237. If *recurse=True*, then objects referred to in the global dictionary
  238. are recursively traced and pickled, instead of the default behavior
  239. of attempting to store the entire global dictionary. This is needed for
  240. functions defined via *exec()*.
  241. *fmode* (:const:`HANDLE_FMODE`, :const:`CONTENTS_FMODE`,
  242. or :const:`FILE_FMODE`) indicates how file handles will be pickled.
  243. For example, when pickling a data file handle for transfer to a remote
  244. compute service, *FILE_FMODE* will include the file contents in the
  245. pickle and cursor position so that a remote method can operate
  246. transparently on an object with an open file handle.
  247. Default values for keyword arguments can be set in :mod:`dill.settings`.
  248. """
  249. file = StringIO()
  250. dump(obj, file, protocol, byref, fmode, recurse, **kwds)#, strictio)
  251. return file.getvalue()
  252. def load(file, ignore=None, **kwds):
  253. """
  254. Unpickle an object from a file.
  255. See :func:`loads` for keyword arguments.
  256. """
  257. return Unpickler(file, ignore=ignore, **kwds).load()
  258. def loads(str, ignore=None, **kwds):
  259. """
  260. Unpickle an object from a string.
  261. If *ignore=False* then objects whose class is defined in the module
  262. *__main__* are updated to reference the existing class in *__main__*,
  263. otherwise they are left to refer to the reconstructed type, which may
  264. be different.
  265. Default values for keyword arguments can be set in :mod:`dill.settings`.
  266. """
  267. file = StringIO(str)
  268. return load(file, ignore, **kwds)
  269. # def dumpzs(obj, protocol=None):
  270. # """pickle an object to a compressed string"""
  271. # return zlib.compress(dumps(obj, protocol))
  272. # def loadzs(str):
  273. # """unpickle an object from a compressed string"""
  274. # return loads(zlib.decompress(str))
  275. ### End: Shorthands ###
  276. class MetaCatchingDict(dict):
  277. def get(self, key, default=None):
  278. try:
  279. return self[key]
  280. except KeyError:
  281. return default
  282. def __missing__(self, key):
  283. if issubclass(key, type):
  284. return save_type
  285. else:
  286. raise KeyError()
  287. class PickleWarning(Warning, PickleError):
  288. pass
  289. class PicklingWarning(PickleWarning, PicklingError):
  290. pass
  291. class UnpicklingWarning(PickleWarning, UnpicklingError):
  292. pass
  293. ### Extend the Picklers
  294. class Pickler(StockPickler):
  295. """python's Pickler extended to interpreter sessions"""
  296. dispatch: typing.Dict[type, typing.Callable[[Pickler, typing.Any], None]] \
  297. = MetaCatchingDict(StockPickler.dispatch.copy())
  298. """The dispatch table, a dictionary of serializing functions used
  299. by Pickler to save objects of specific types. Use :func:`pickle`
  300. or :func:`register` to associate types to custom functions.
  301. :meta hide-value:
  302. """
  303. _session = False
  304. from .settings import settings
  305. def __init__(self, file, *args, **kwds):
  306. settings = Pickler.settings
  307. _byref = kwds.pop('byref', None)
  308. #_strictio = kwds.pop('strictio', None)
  309. _fmode = kwds.pop('fmode', None)
  310. _recurse = kwds.pop('recurse', None)
  311. StockPickler.__init__(self, file, *args, **kwds)
  312. self._main = _main_module
  313. self._diff_cache = {}
  314. self._byref = settings['byref'] if _byref is None else _byref
  315. self._strictio = False #_strictio
  316. self._fmode = settings['fmode'] if _fmode is None else _fmode
  317. self._recurse = settings['recurse'] if _recurse is None else _recurse
  318. self._postproc = OrderedDict()
  319. self._file = file
  320. def save(self, obj, save_persistent_id=True):
  321. # numpy hack
  322. obj_type = type(obj)
  323. if NumpyArrayType and not (obj_type is type or obj_type in Pickler.dispatch):
  324. # register if the object is a numpy ufunc
  325. # thanks to Paul Kienzle for pointing out ufuncs didn't pickle
  326. if numpyufunc(obj_type):
  327. @register(obj_type)
  328. def save_numpy_ufunc(pickler, obj):
  329. logger.trace(pickler, "Nu: %s", obj)
  330. name = getattr(obj, '__qualname__', getattr(obj, '__name__', None))
  331. StockPickler.save_global(pickler, obj, name=name)
  332. logger.trace(pickler, "# Nu")
  333. return
  334. # NOTE: the above 'save' performs like:
  335. # import copy_reg
  336. # def udump(f): return f.__name__
  337. # def uload(name): return getattr(numpy, name)
  338. # copy_reg.pickle(NumpyUfuncType, udump, uload)
  339. # register if the object is a numpy dtype
  340. if numpydtype(obj_type):
  341. @register(obj_type)
  342. def save_numpy_dtype(pickler, obj):
  343. logger.trace(pickler, "Dt: %s", obj)
  344. pickler.save_reduce(_create_dtypemeta, (obj.type,), obj=obj)
  345. logger.trace(pickler, "# Dt")
  346. return
  347. # NOTE: the above 'save' performs like:
  348. # import copy_reg
  349. # def uload(name): return type(NumpyDType(name))
  350. # def udump(f): return uload, (f.type,)
  351. # copy_reg.pickle(NumpyDTypeType, udump, uload)
  352. # register if the object is a subclassed numpy array instance
  353. if ndarraysubclassinstance(obj_type):
  354. @register(obj_type)
  355. def save_numpy_array(pickler, obj):
  356. logger.trace(pickler, "Nu: (%s, %s)", obj.shape, obj.dtype)
  357. npdict = getattr(obj, '__dict__', None)
  358. f, args, state = obj.__reduce__()
  359. pickler.save_reduce(_create_array, (f,args,state,npdict), obj=obj)
  360. logger.trace(pickler, "# Nu")
  361. return
  362. # end numpy hack
  363. if GENERATOR_FAIL and obj_type is GeneratorType:
  364. msg = "Can't pickle %s: attribute lookup builtins.generator failed" % GeneratorType
  365. raise PicklingError(msg)
  366. StockPickler.save(self, obj, save_persistent_id)
  367. save.__doc__ = StockPickler.save.__doc__
  368. def dump(self, obj): #NOTE: if settings change, need to update attributes
  369. logger.trace_setup(self)
  370. StockPickler.dump(self, obj)
  371. dump.__doc__ = StockPickler.dump.__doc__
  372. class Unpickler(StockUnpickler):
  373. """python's Unpickler extended to interpreter sessions and more types"""
  374. from .settings import settings
  375. _session = False
  376. def find_class(self, module, name):
  377. if (module, name) == ('__builtin__', '__main__'):
  378. return self._main.__dict__ #XXX: above set w/save_module_dict
  379. elif (module, name) == ('__builtin__', 'NoneType'):
  380. return type(None) #XXX: special case: NoneType missing
  381. if module == 'dill.dill': module = 'dill._dill'
  382. return StockUnpickler.find_class(self, module, name)
  383. def __init__(self, *args, **kwds):
  384. settings = Pickler.settings
  385. _ignore = kwds.pop('ignore', None)
  386. StockUnpickler.__init__(self, *args, **kwds)
  387. self._main = _main_module
  388. self._ignore = settings['ignore'] if _ignore is None else _ignore
  389. def load(self): #NOTE: if settings change, need to update attributes
  390. obj = StockUnpickler.load(self)
  391. if type(obj).__module__ == getattr(_main_module, '__name__', '__main__'):
  392. if not self._ignore:
  393. # point obj class to main
  394. try: obj.__class__ = getattr(self._main, type(obj).__name__)
  395. except (AttributeError,TypeError): pass # defined in a file
  396. #_main_module.__dict__.update(obj.__dict__) #XXX: should update globals ?
  397. return obj
  398. load.__doc__ = StockUnpickler.load.__doc__
  399. pass
  400. '''
  401. def dispatch_table():
  402. """get the dispatch table of registered types"""
  403. return Pickler.dispatch
  404. '''
  405. pickle_dispatch_copy = StockPickler.dispatch.copy()
  406. def pickle(t, func):
  407. """expose :attr:`~Pickler.dispatch` table for user-created extensions"""
  408. Pickler.dispatch[t] = func
  409. return
  410. def register(t):
  411. """decorator to register types to Pickler's :attr:`~Pickler.dispatch` table"""
  412. def proxy(func):
  413. Pickler.dispatch[t] = func
  414. return func
  415. return proxy
  416. def _revert_extension():
  417. """drop dill-registered types from pickle's dispatch table"""
  418. for type, func in list(StockPickler.dispatch.items()):
  419. if func.__module__ == __name__:
  420. del StockPickler.dispatch[type]
  421. if type in pickle_dispatch_copy:
  422. StockPickler.dispatch[type] = pickle_dispatch_copy[type]
  423. def use_diff(on=True):
  424. """
  425. Reduces size of pickles by only including object which have changed.
  426. Decreases pickle size but increases CPU time needed.
  427. Also helps avoid some unpickleable objects.
  428. MUST be called at start of script, otherwise changes will not be recorded.
  429. """
  430. global _use_diff, diff
  431. _use_diff = on
  432. if _use_diff and diff is None:
  433. try:
  434. from . import diff as d
  435. except ImportError:
  436. import diff as d
  437. diff = d
  438. def _create_typemap():
  439. import types
  440. d = dict(list(__builtin__.__dict__.items()) + \
  441. list(types.__dict__.items())).items()
  442. for key, value in d:
  443. if getattr(value, '__module__', None) == 'builtins' \
  444. and type(value) is type:
  445. yield key, value
  446. return
  447. _reverse_typemap = dict(_create_typemap())
  448. _reverse_typemap.update({
  449. 'PartialType': PartialType,
  450. 'SuperType': SuperType,
  451. 'ItemGetterType': ItemGetterType,
  452. 'AttrGetterType': AttrGetterType,
  453. })
  454. if sys.hexversion < 0x30800a2:
  455. _reverse_typemap.update({
  456. 'CellType': CellType,
  457. })
  458. # "Incidental" implementation specific types. Unpickling these types in another
  459. # implementation of Python (PyPy -> CPython) is not guaranteed to work
  460. # This dictionary should contain all types that appear in Python implementations
  461. # but are not defined in https://docs.python.org/3/library/types.html#standard-interpreter-types
  462. x=OrderedDict()
  463. _incedental_reverse_typemap = {
  464. 'FileType': FileType,
  465. 'BufferedRandomType': BufferedRandomType,
  466. 'BufferedReaderType': BufferedReaderType,
  467. 'BufferedWriterType': BufferedWriterType,
  468. 'TextWrapperType': TextWrapperType,
  469. 'PyBufferedRandomType': PyBufferedRandomType,
  470. 'PyBufferedReaderType': PyBufferedReaderType,
  471. 'PyBufferedWriterType': PyBufferedWriterType,
  472. 'PyTextWrapperType': PyTextWrapperType,
  473. }
  474. _incedental_reverse_typemap.update({
  475. "DictKeysType": type({}.keys()),
  476. "DictValuesType": type({}.values()),
  477. "DictItemsType": type({}.items()),
  478. "OdictKeysType": type(x.keys()),
  479. "OdictValuesType": type(x.values()),
  480. "OdictItemsType": type(x.items()),
  481. })
  482. if ExitType:
  483. _incedental_reverse_typemap['ExitType'] = ExitType
  484. if InputType:
  485. _incedental_reverse_typemap['InputType'] = InputType
  486. _incedental_reverse_typemap['OutputType'] = OutputType
  487. '''
  488. try:
  489. import symtable
  490. _incedental_reverse_typemap["SymtableEntryType"] = type(symtable.symtable("", "string", "exec")._table)
  491. except: #FIXME: fails to pickle
  492. pass
  493. if sys.hexversion >= 0x30a00a0:
  494. _incedental_reverse_typemap['LineIteratorType'] = type(compile('3', '', 'eval').co_lines())
  495. '''
  496. if sys.hexversion >= 0x30b00b0:
  497. from types import GenericAlias
  498. _incedental_reverse_typemap["GenericAliasIteratorType"] = type(iter(GenericAlias(list, (int,))))
  499. '''
  500. _incedental_reverse_typemap['PositionsIteratorType'] = type(compile('3', '', 'eval').co_positions())
  501. '''
  502. try:
  503. import winreg
  504. _incedental_reverse_typemap["HKEYType"] = winreg.HKEYType
  505. except ImportError:
  506. pass
  507. _reverse_typemap.update(_incedental_reverse_typemap)
  508. _incedental_types = set(_incedental_reverse_typemap.values())
  509. del x
  510. _typemap = dict((v, k) for k, v in _reverse_typemap.items())
  511. def _unmarshal(string):
  512. return marshal.loads(string)
  513. def _load_type(name):
  514. return _reverse_typemap[name]
  515. def _create_type(typeobj, *args):
  516. return typeobj(*args)
  517. def _create_function(fcode, fglobals, fname=None, fdefaults=None,
  518. fclosure=None, fdict=None, fkwdefaults=None):
  519. # same as FunctionType, but enable passing __dict__ to new function,
  520. # __dict__ is the storehouse for attributes added after function creation
  521. func = FunctionType(fcode, fglobals or dict(), fname, fdefaults, fclosure)
  522. if fdict is not None:
  523. func.__dict__.update(fdict) #XXX: better copy? option to copy?
  524. if fkwdefaults is not None:
  525. func.__kwdefaults__ = fkwdefaults
  526. # 'recurse' only stores referenced modules/objects in fglobals,
  527. # thus we need to make sure that we have __builtins__ as well
  528. if "__builtins__" not in func.__globals__:
  529. func.__globals__["__builtins__"] = globals()["__builtins__"]
  530. # assert id(fglobals) == id(func.__globals__)
  531. return func
  532. class match:
  533. """
  534. Make avaialable a limited structural pattern matching-like syntax for Python < 3.10
  535. Patterns can be only tuples (without types) currently.
  536. Inspired by the package pattern-matching-PEP634.
  537. Usage:
  538. >>> with match(args) as m:
  539. >>> if m.case(('x', 'y')):
  540. >>> # use m.x and m.y
  541. >>> elif m.case(('x', 'y', 'z')):
  542. >>> # use m.x, m.y and m.z
  543. Equivalent native code for Python >= 3.10:
  544. >>> match args:
  545. >>> case (x, y):
  546. >>> # use x and y
  547. >>> case (x, y, z):
  548. >>> # use x, y and z
  549. """
  550. def __init__(self, value):
  551. self.value = value
  552. self._fields = None
  553. def __enter__(self):
  554. return self
  555. def __exit__(self, *exc_info):
  556. return False
  557. def case(self, args): # *args, **kwargs):
  558. """just handles tuple patterns"""
  559. if len(self.value) != len(args): # + len(kwargs):
  560. return False
  561. #if not all(isinstance(arg, pat) for arg, pat in zip(self.value[len(args):], kwargs.values())):
  562. # return False
  563. self.args = args # (*args, *kwargs)
  564. return True
  565. @property
  566. def fields(self):
  567. # Only bind names to values if necessary.
  568. if self._fields is None:
  569. self._fields = dict(zip(self.args, self.value))
  570. return self._fields
  571. def __getattr__(self, item):
  572. return self.fields[item]
  573. ALL_CODE_PARAMS = [
  574. # Version New attribute CodeType parameters
  575. ((3,11,'a'), 'co_endlinetable', 'argcount posonlyargcount kwonlyargcount nlocals stacksize flags code consts names varnames filename name qualname firstlineno linetable endlinetable columntable exceptiontable freevars cellvars'),
  576. ((3,11), 'co_exceptiontable', 'argcount posonlyargcount kwonlyargcount nlocals stacksize flags code consts names varnames filename name qualname firstlineno linetable exceptiontable freevars cellvars'),
  577. ((3,10), 'co_linetable', 'argcount posonlyargcount kwonlyargcount nlocals stacksize flags code consts names varnames filename name firstlineno linetable freevars cellvars'),
  578. ((3,8), 'co_posonlyargcount', 'argcount posonlyargcount kwonlyargcount nlocals stacksize flags code consts names varnames filename name firstlineno lnotab freevars cellvars'),
  579. ((3,7), 'co_kwonlyargcount', 'argcount kwonlyargcount nlocals stacksize flags code consts names varnames filename name firstlineno lnotab freevars cellvars'),
  580. ]
  581. for version, new_attr, params in ALL_CODE_PARAMS:
  582. if hasattr(CodeType, new_attr):
  583. CODE_VERSION = version
  584. CODE_PARAMS = params.split()
  585. break
  586. ENCODE_PARAMS = set(CODE_PARAMS).intersection(
  587. ['code', 'lnotab', 'linetable', 'endlinetable', 'columntable', 'exceptiontable'])
  588. def _create_code(*args):
  589. if not isinstance(args[0], int): # co_lnotab stored from >= 3.10
  590. LNOTAB, *args = args
  591. else: # from < 3.10 (or pre-LNOTAB storage)
  592. LNOTAB = b''
  593. with match(args) as m:
  594. # Python 3.11/3.12a (18 members)
  595. if m.case((
  596. 'argcount', 'posonlyargcount', 'kwonlyargcount', 'nlocals', 'stacksize', 'flags', # args[0:6]
  597. 'code', 'consts', 'names', 'varnames', 'filename', 'name', 'qualname', 'firstlineno', # args[6:14]
  598. 'linetable', 'exceptiontable', 'freevars', 'cellvars' # args[14:]
  599. )):
  600. if CODE_VERSION == (3,11):
  601. return CodeType(
  602. *args[:6],
  603. args[6].encode() if hasattr(args[6], 'encode') else args[6], # code
  604. *args[7:14],
  605. args[14].encode() if hasattr(args[14], 'encode') else args[14], # linetable
  606. args[15].encode() if hasattr(args[15], 'encode') else args[15], # exceptiontable
  607. args[16],
  608. args[17],
  609. )
  610. fields = m.fields
  611. # Python 3.10 or 3.8/3.9 (16 members)
  612. elif m.case((
  613. 'argcount', 'posonlyargcount', 'kwonlyargcount', 'nlocals', 'stacksize', 'flags', # args[0:6]
  614. 'code', 'consts', 'names', 'varnames', 'filename', 'name', 'firstlineno', # args[6:13]
  615. 'LNOTAB_OR_LINETABLE', 'freevars', 'cellvars' # args[13:]
  616. )):
  617. if CODE_VERSION == (3,10) or CODE_VERSION == (3,8):
  618. return CodeType(
  619. *args[:6],
  620. args[6].encode() if hasattr(args[6], 'encode') else args[6], # code
  621. *args[7:13],
  622. args[13].encode() if hasattr(args[13], 'encode') else args[13], # lnotab/linetable
  623. args[14],
  624. args[15],
  625. )
  626. fields = m.fields
  627. if CODE_VERSION >= (3,10):
  628. fields['linetable'] = m.LNOTAB_OR_LINETABLE
  629. else:
  630. fields['lnotab'] = LNOTAB if LNOTAB else m.LNOTAB_OR_LINETABLE
  631. # Python 3.7 (15 args)
  632. elif m.case((
  633. 'argcount', 'kwonlyargcount', 'nlocals', 'stacksize', 'flags', # args[0:5]
  634. 'code', 'consts', 'names', 'varnames', 'filename', 'name', 'firstlineno', # args[5:12]
  635. 'lnotab', 'freevars', 'cellvars' # args[12:]
  636. )):
  637. if CODE_VERSION == (3,7):
  638. return CodeType(
  639. *args[:5],
  640. args[5].encode() if hasattr(args[5], 'encode') else args[5], # code
  641. *args[6:12],
  642. args[12].encode() if hasattr(args[12], 'encode') else args[12], # lnotab
  643. args[13],
  644. args[14],
  645. )
  646. fields = m.fields
  647. # Python 3.11a (20 members)
  648. elif m.case((
  649. 'argcount', 'posonlyargcount', 'kwonlyargcount', 'nlocals', 'stacksize', 'flags', # args[0:6]
  650. 'code', 'consts', 'names', 'varnames', 'filename', 'name', 'qualname', 'firstlineno', # args[6:14]
  651. 'linetable', 'endlinetable', 'columntable', 'exceptiontable', 'freevars', 'cellvars' # args[14:]
  652. )):
  653. if CODE_VERSION == (3,11,'a'):
  654. return CodeType(
  655. *args[:6],
  656. args[6].encode() if hasattr(args[6], 'encode') else args[6], # code
  657. *args[7:14],
  658. *(a.encode() if hasattr(a, 'encode') else a for a in args[14:18]), # linetable-exceptiontable
  659. args[18],
  660. args[19],
  661. )
  662. fields = m.fields
  663. else:
  664. raise UnpicklingError("pattern match for code object failed")
  665. # The args format doesn't match this version.
  666. fields.setdefault('posonlyargcount', 0) # from python <= 3.7
  667. fields.setdefault('lnotab', LNOTAB) # from python >= 3.10
  668. fields.setdefault('linetable', b'') # from python <= 3.9
  669. fields.setdefault('qualname', fields['name']) # from python <= 3.10
  670. fields.setdefault('exceptiontable', b'') # from python <= 3.10
  671. fields.setdefault('endlinetable', None) # from python != 3.11a
  672. fields.setdefault('columntable', None) # from python != 3.11a
  673. args = (fields[k].encode() if k in ENCODE_PARAMS and hasattr(fields[k], 'encode') else fields[k]
  674. for k in CODE_PARAMS)
  675. return CodeType(*args)
  676. def _create_ftype(ftypeobj, func, args, kwds):
  677. if kwds is None:
  678. kwds = {}
  679. if args is None:
  680. args = ()
  681. return ftypeobj(func, *args, **kwds)
  682. def _create_typing_tuple(argz, *args): #NOTE: workaround python/cpython#94245
  683. if not argz:
  684. return typing.Tuple[()].copy_with(())
  685. if argz == ((),):
  686. return typing.Tuple[()]
  687. return typing.Tuple[argz]
  688. def _create_lock(locked, *args): #XXX: ignores 'blocking'
  689. from threading import Lock
  690. lock = Lock()
  691. if locked:
  692. if not lock.acquire(False):
  693. raise UnpicklingError("Cannot acquire lock")
  694. return lock
  695. def _create_rlock(count, owner, *args): #XXX: ignores 'blocking'
  696. lock = RLockType()
  697. if owner is not None:
  698. lock._acquire_restore((count, owner))
  699. if owner and not lock._is_owned():
  700. raise UnpicklingError("Cannot acquire lock")
  701. return lock
  702. # thanks to matsjoyce for adding all the different file modes
  703. def _create_filehandle(name, mode, position, closed, open, strictio, fmode, fdata): # buffering=0
  704. # only pickles the handle, not the file contents... good? or StringIO(data)?
  705. # (for file contents see: http://effbot.org/librarybook/copy-reg.htm)
  706. # NOTE: handle special cases first (are there more special cases?)
  707. names = {'<stdin>':sys.__stdin__, '<stdout>':sys.__stdout__,
  708. '<stderr>':sys.__stderr__} #XXX: better fileno=(0,1,2) ?
  709. if name in list(names.keys()):
  710. f = names[name] #XXX: safer "f=sys.stdin"
  711. elif name == '<tmpfile>':
  712. f = os.tmpfile()
  713. elif name == '<fdopen>':
  714. import tempfile
  715. f = tempfile.TemporaryFile(mode)
  716. else:
  717. try:
  718. exists = os.path.exists(name)
  719. except Exception:
  720. exists = False
  721. if not exists:
  722. if strictio:
  723. raise FileNotFoundError("[Errno 2] No such file or directory: '%s'" % name)
  724. elif "r" in mode and fmode != FILE_FMODE:
  725. name = '<fdopen>' # or os.devnull?
  726. current_size = 0 # or maintain position?
  727. else:
  728. current_size = os.path.getsize(name)
  729. if position > current_size:
  730. if strictio:
  731. raise ValueError("invalid buffer size")
  732. elif fmode == CONTENTS_FMODE:
  733. position = current_size
  734. # try to open the file by name
  735. # NOTE: has different fileno
  736. try:
  737. #FIXME: missing: *buffering*, encoding, softspace
  738. if fmode == FILE_FMODE:
  739. f = open(name, mode if "w" in mode else "w")
  740. f.write(fdata)
  741. if "w" not in mode:
  742. f.close()
  743. f = open(name, mode)
  744. elif name == '<fdopen>': # file did not exist
  745. import tempfile
  746. f = tempfile.TemporaryFile(mode)
  747. # treat x mode as w mode
  748. elif fmode == CONTENTS_FMODE \
  749. and ("w" in mode or "x" in mode):
  750. # stop truncation when opening
  751. flags = os.O_CREAT
  752. if "+" in mode:
  753. flags |= os.O_RDWR
  754. else:
  755. flags |= os.O_WRONLY
  756. f = os.fdopen(os.open(name, flags), mode)
  757. # set name to the correct value
  758. r = getattr(f, "buffer", f)
  759. r = getattr(r, "raw", r)
  760. r.name = name
  761. assert f.name == name
  762. else:
  763. f = open(name, mode)
  764. except (IOError, FileNotFoundError):
  765. err = sys.exc_info()[1]
  766. raise UnpicklingError(err)
  767. if closed:
  768. f.close()
  769. elif position >= 0 and fmode != HANDLE_FMODE:
  770. f.seek(position)
  771. return f
  772. def _create_stringi(value, position, closed):
  773. f = StringIO(value)
  774. if closed: f.close()
  775. else: f.seek(position)
  776. return f
  777. def _create_stringo(value, position, closed):
  778. f = StringIO()
  779. if closed: f.close()
  780. else:
  781. f.write(value)
  782. f.seek(position)
  783. return f
  784. class _itemgetter_helper(object):
  785. def __init__(self):
  786. self.items = []
  787. def __getitem__(self, item):
  788. self.items.append(item)
  789. return
  790. class _attrgetter_helper(object):
  791. def __init__(self, attrs, index=None):
  792. self.attrs = attrs
  793. self.index = index
  794. def __getattribute__(self, attr):
  795. attrs = object.__getattribute__(self, "attrs")
  796. index = object.__getattribute__(self, "index")
  797. if index is None:
  798. index = len(attrs)
  799. attrs.append(attr)
  800. else:
  801. attrs[index] = ".".join([attrs[index], attr])
  802. return type(self)(attrs, index)
  803. class _dictproxy_helper(dict):
  804. def __ror__(self, a):
  805. return a
  806. _dictproxy_helper_instance = _dictproxy_helper()
  807. __d = {}
  808. try:
  809. # In CPython 3.9 and later, this trick can be used to exploit the
  810. # implementation of the __or__ function of MappingProxyType to get the true
  811. # mapping referenced by the proxy. It may work for other implementations,
  812. # but is not guaranteed.
  813. MAPPING_PROXY_TRICK = __d is (DictProxyType(__d) | _dictproxy_helper_instance)
  814. except Exception:
  815. MAPPING_PROXY_TRICK = False
  816. del __d
  817. # _CELL_REF and _CELL_EMPTY are used to stay compatible with versions of dill
  818. # whose _create_cell functions do not have a default value.
  819. # _CELL_REF can be safely removed entirely (replaced by empty tuples for calls
  820. # to _create_cell) once breaking changes are allowed.
  821. _CELL_REF = None
  822. _CELL_EMPTY = Sentinel('_CELL_EMPTY')
  823. def _create_cell(contents=None):
  824. if contents is not _CELL_EMPTY:
  825. value = contents
  826. return (lambda: value).__closure__[0]
  827. def _create_weakref(obj, *args):
  828. from weakref import ref
  829. if obj is None: # it's dead
  830. from collections import UserDict
  831. return ref(UserDict(), *args)
  832. return ref(obj, *args)
  833. def _create_weakproxy(obj, callable=False, *args):
  834. from weakref import proxy
  835. if obj is None: # it's dead
  836. if callable: return proxy(lambda x:x, *args)
  837. from collections import UserDict
  838. return proxy(UserDict(), *args)
  839. return proxy(obj, *args)
  840. def _eval_repr(repr_str):
  841. return eval(repr_str)
  842. def _create_array(f, args, state, npdict=None):
  843. #array = numpy.core.multiarray._reconstruct(*args)
  844. array = f(*args)
  845. array.__setstate__(state)
  846. if npdict is not None: # we also have saved state in __dict__
  847. array.__dict__.update(npdict)
  848. return array
  849. def _create_dtypemeta(scalar_type):
  850. if NumpyDType is True: __hook__() # a bit hacky I think
  851. if scalar_type is None:
  852. return NumpyDType
  853. return type(NumpyDType(scalar_type))
  854. def _create_namedtuple(name, fieldnames, modulename, defaults=None):
  855. class_ = _import_module(modulename + '.' + name, safe=True)
  856. if class_ is not None:
  857. return class_
  858. import collections
  859. t = collections.namedtuple(name, fieldnames, defaults=defaults, module=modulename)
  860. return t
  861. def _create_capsule(pointer, name, context, destructor):
  862. attr_found = False
  863. try:
  864. # based on https://github.com/python/cpython/blob/f4095e53ab708d95e019c909d5928502775ba68f/Objects/capsule.c#L209-L231
  865. uname = name.decode('utf8')
  866. for i in range(1, uname.count('.')+1):
  867. names = uname.rsplit('.', i)
  868. try:
  869. module = __import__(names[0])
  870. except ImportError:
  871. pass
  872. obj = module
  873. for attr in names[1:]:
  874. obj = getattr(obj, attr)
  875. capsule = obj
  876. attr_found = True
  877. break
  878. except Exception:
  879. pass
  880. if attr_found:
  881. if _PyCapsule_IsValid(capsule, name):
  882. return capsule
  883. raise UnpicklingError("%s object exists at %s but a PyCapsule object was expected." % (type(capsule), name))
  884. else:
  885. #warnings.warn('Creating a new PyCapsule %s for a C data structure that may not be present in memory. Segmentation faults or other memory errors are possible.' % (name,), UnpicklingWarning)
  886. capsule = _PyCapsule_New(pointer, name, destructor)
  887. _PyCapsule_SetContext(capsule, context)
  888. return capsule
  889. def _getattr(objclass, name, repr_str):
  890. # hack to grab the reference directly
  891. try: #XXX: works only for __builtin__ ?
  892. attr = repr_str.split("'")[3]
  893. return eval(attr+'.__dict__["'+name+'"]')
  894. except Exception:
  895. try:
  896. attr = objclass.__dict__
  897. if type(attr) is DictProxyType:
  898. attr = attr[name]
  899. else:
  900. attr = getattr(objclass,name)
  901. except (AttributeError, KeyError):
  902. attr = getattr(objclass,name)
  903. return attr
  904. def _get_attr(self, name):
  905. # stop recursive pickling
  906. return getattr(self, name, None) or getattr(__builtin__, name)
  907. def _import_module(import_name, safe=False):
  908. try:
  909. if import_name.startswith('__runtime__.'):
  910. return sys.modules[import_name]
  911. elif '.' in import_name:
  912. items = import_name.split('.')
  913. module = '.'.join(items[:-1])
  914. obj = items[-1]
  915. else:
  916. return __import__(import_name)
  917. return getattr(__import__(module, None, None, [obj]), obj)
  918. except (ImportError, AttributeError, KeyError):
  919. if safe:
  920. return None
  921. raise
  922. # https://github.com/python/cpython/blob/a8912a0f8d9eba6d502c37d522221f9933e976db/Lib/pickle.py#L322-L333
  923. def _getattribute(obj, name):
  924. for subpath in name.split('.'):
  925. if subpath == '<locals>':
  926. raise AttributeError("Can't get local attribute {!r} on {!r}"
  927. .format(name, obj))
  928. try:
  929. parent = obj
  930. obj = getattr(obj, subpath)
  931. except AttributeError:
  932. raise AttributeError("Can't get attribute {!r} on {!r}"
  933. .format(name, obj))
  934. return obj, parent
  935. def _locate_function(obj, pickler=None):
  936. module_name = getattr(obj, '__module__', None)
  937. if module_name in ['__main__', None] or \
  938. pickler and is_dill(pickler, child=False) and pickler._session and module_name == pickler._main.__name__:
  939. return False
  940. if hasattr(obj, '__qualname__'):
  941. module = _import_module(module_name, safe=True)
  942. try:
  943. found, _ = _getattribute(module, obj.__qualname__)
  944. return found is obj
  945. except AttributeError:
  946. return False
  947. else:
  948. found = _import_module(module_name + '.' + obj.__name__, safe=True)
  949. return found is obj
  950. def _setitems(dest, source):
  951. for k, v in source.items():
  952. dest[k] = v
  953. def _save_with_postproc(pickler, reduction, is_pickler_dill=None, obj=Getattr.NO_DEFAULT, postproc_list=None):
  954. if obj is Getattr.NO_DEFAULT:
  955. obj = Reduce(reduction) # pragma: no cover
  956. if is_pickler_dill is None:
  957. is_pickler_dill = is_dill(pickler, child=True)
  958. if is_pickler_dill:
  959. # assert id(obj) not in pickler._postproc, str(obj) + ' already pushed on stack!'
  960. # if not hasattr(pickler, 'x'): pickler.x = 0
  961. # print(pickler.x*' ', 'push', obj, id(obj), pickler._recurse)
  962. # pickler.x += 1
  963. if postproc_list is None:
  964. postproc_list = []
  965. # Recursive object not supported. Default to a global instead.
  966. if id(obj) in pickler._postproc:
  967. name = '%s.%s ' % (obj.__module__, getattr(obj, '__qualname__', obj.__name__)) if hasattr(obj, '__module__') else ''
  968. warnings.warn('Cannot pickle %r: %shas recursive self-references that trigger a RecursionError.' % (obj, name), PicklingWarning)
  969. pickler.save_global(obj)
  970. return
  971. pickler._postproc[id(obj)] = postproc_list
  972. # TODO: Use state_setter in Python 3.8 to allow for faster cPickle implementations
  973. pickler.save_reduce(*reduction, obj=obj)
  974. if is_pickler_dill:
  975. # pickler.x -= 1
  976. # print(pickler.x*' ', 'pop', obj, id(obj))
  977. postproc = pickler._postproc.pop(id(obj))
  978. # assert postproc_list == postproc, 'Stack tampered!'
  979. for reduction in reversed(postproc):
  980. if reduction[0] is _setitems:
  981. # use the internal machinery of pickle.py to speedup when
  982. # updating a dictionary in postproc
  983. dest, source = reduction[1]
  984. if source:
  985. pickler.write(pickler.get(pickler.memo[id(dest)][0]))
  986. pickler._batch_setitems(iter(source.items()))
  987. else:
  988. # Updating with an empty dictionary. Same as doing nothing.
  989. continue
  990. else:
  991. pickler.save_reduce(*reduction)
  992. # pop None created by calling preprocessing step off stack
  993. pickler.write(POP)
  994. #@register(CodeType)
  995. #def save_code(pickler, obj):
  996. # logger.trace(pickler, "Co: %s", obj)
  997. # pickler.save_reduce(_unmarshal, (marshal.dumps(obj),), obj=obj)
  998. # logger.trace(pickler, "# Co")
  999. # return
  1000. # The following function is based on 'save_codeobject' from 'cloudpickle'
  1001. # Copyright (c) 2012, Regents of the University of California.
  1002. # Copyright (c) 2009 `PiCloud, Inc. <http://www.picloud.com>`_.
  1003. # License: https://github.com/cloudpipe/cloudpickle/blob/master/LICENSE
  1004. @register(CodeType)
  1005. def save_code(pickler, obj):
  1006. logger.trace(pickler, "Co: %s", obj)
  1007. if hasattr(obj, "co_endlinetable"): # python 3.11a (20 args)
  1008. args = (
  1009. obj.co_lnotab, # for < python 3.10 [not counted in args]
  1010. obj.co_argcount, obj.co_posonlyargcount,
  1011. obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
  1012. obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
  1013. obj.co_varnames, obj.co_filename, obj.co_name, obj.co_qualname,
  1014. obj.co_firstlineno, obj.co_linetable, obj.co_endlinetable,
  1015. obj.co_columntable, obj.co_exceptiontable, obj.co_freevars,
  1016. obj.co_cellvars
  1017. )
  1018. elif hasattr(obj, "co_exceptiontable"): # python 3.11 (18 args)
  1019. with warnings.catch_warnings():
  1020. if not OLD312a7: # issue 597
  1021. warnings.filterwarnings('ignore', category=DeprecationWarning)
  1022. args = (
  1023. obj.co_lnotab, # for < python 3.10 [not counted in args]
  1024. obj.co_argcount, obj.co_posonlyargcount,
  1025. obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
  1026. obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
  1027. obj.co_varnames, obj.co_filename, obj.co_name, obj.co_qualname,
  1028. obj.co_firstlineno, obj.co_linetable, obj.co_exceptiontable,
  1029. obj.co_freevars, obj.co_cellvars
  1030. )
  1031. elif hasattr(obj, "co_linetable"): # python 3.10 (16 args)
  1032. args = (
  1033. obj.co_lnotab, # for < python 3.10 [not counted in args]
  1034. obj.co_argcount, obj.co_posonlyargcount,
  1035. obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
  1036. obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
  1037. obj.co_varnames, obj.co_filename, obj.co_name,
  1038. obj.co_firstlineno, obj.co_linetable, obj.co_freevars,
  1039. obj.co_cellvars
  1040. )
  1041. elif hasattr(obj, "co_posonlyargcount"): # python 3.8 (16 args)
  1042. args = (
  1043. obj.co_argcount, obj.co_posonlyargcount,
  1044. obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
  1045. obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
  1046. obj.co_varnames, obj.co_filename, obj.co_name,
  1047. obj.co_firstlineno, obj.co_lnotab, obj.co_freevars,
  1048. obj.co_cellvars
  1049. )
  1050. else: # python 3.7 (15 args)
  1051. args = (
  1052. obj.co_argcount, obj.co_kwonlyargcount, obj.co_nlocals,
  1053. obj.co_stacksize, obj.co_flags, obj.co_code, obj.co_consts,
  1054. obj.co_names, obj.co_varnames, obj.co_filename,
  1055. obj.co_name, obj.co_firstlineno, obj.co_lnotab,
  1056. obj.co_freevars, obj.co_cellvars
  1057. )
  1058. pickler.save_reduce(_create_code, args, obj=obj)
  1059. logger.trace(pickler, "# Co")
  1060. return
  1061. def _repr_dict(obj):
  1062. """Make a short string representation of a dictionary."""
  1063. return "<%s object at %#012x>" % (type(obj).__name__, id(obj))
  1064. @register(dict)
  1065. def save_module_dict(pickler, obj):
  1066. if is_dill(pickler, child=False) and obj == pickler._main.__dict__ and \
  1067. not (pickler._session and pickler._first_pass):
  1068. logger.trace(pickler, "D1: %s", _repr_dict(obj)) # obj
  1069. pickler.write(bytes('c__builtin__\n__main__\n', 'UTF-8'))
  1070. logger.trace(pickler, "# D1")
  1071. elif (not is_dill(pickler, child=False)) and (obj == _main_module.__dict__):
  1072. logger.trace(pickler, "D3: %s", _repr_dict(obj)) # obj
  1073. pickler.write(bytes('c__main__\n__dict__\n', 'UTF-8')) #XXX: works in general?
  1074. logger.trace(pickler, "# D3")
  1075. elif '__name__' in obj and obj != _main_module.__dict__ \
  1076. and type(obj['__name__']) is str \
  1077. and obj is getattr(_import_module(obj['__name__'],True), '__dict__', None):
  1078. logger.trace(pickler, "D4: %s", _repr_dict(obj)) # obj
  1079. pickler.write(bytes('c%s\n__dict__\n' % obj['__name__'], 'UTF-8'))
  1080. logger.trace(pickler, "# D4")
  1081. else:
  1082. logger.trace(pickler, "D2: %s", _repr_dict(obj)) # obj
  1083. if is_dill(pickler, child=False) and pickler._session:
  1084. # we only care about session the first pass thru
  1085. pickler._first_pass = False
  1086. StockPickler.save_dict(pickler, obj)
  1087. logger.trace(pickler, "# D2")
  1088. return
  1089. if not OLD310 and MAPPING_PROXY_TRICK:
  1090. def save_dict_view(dicttype):
  1091. def save_dict_view_for_function(func):
  1092. def _save_dict_view(pickler, obj):
  1093. logger.trace(pickler, "Dkvi: <%s>", obj)
  1094. mapping = obj.mapping | _dictproxy_helper_instance
  1095. pickler.save_reduce(func, (mapping,), obj=obj)
  1096. logger.trace(pickler, "# Dkvi")
  1097. return _save_dict_view
  1098. return [
  1099. (funcname, save_dict_view_for_function(getattr(dicttype, funcname)))
  1100. for funcname in ('keys', 'values', 'items')
  1101. ]
  1102. else:
  1103. # The following functions are based on 'cloudpickle'
  1104. # https://github.com/cloudpipe/cloudpickle/blob/5d89947288a18029672596a4d719093cc6d5a412/cloudpickle/cloudpickle.py#L922-L940
  1105. # Copyright (c) 2012, Regents of the University of California.
  1106. # Copyright (c) 2009 `PiCloud, Inc. <http://www.picloud.com>`_.
  1107. # License: https://github.com/cloudpipe/cloudpickle/blob/master/LICENSE
  1108. def save_dict_view(dicttype):
  1109. def save_dict_keys(pickler, obj):
  1110. logger.trace(pickler, "Dk: <%s>", obj)
  1111. dict_constructor = _shims.Reduce(dicttype.fromkeys, (list(obj),))
  1112. pickler.save_reduce(dicttype.keys, (dict_constructor,), obj=obj)
  1113. logger.trace(pickler, "# Dk")
  1114. def save_dict_values(pickler, obj):
  1115. logger.trace(pickler, "Dv: <%s>", obj)
  1116. dict_constructor = _shims.Reduce(dicttype, (enumerate(obj),))
  1117. pickler.save_reduce(dicttype.values, (dict_constructor,), obj=obj)
  1118. logger.trace(pickler, "# Dv")
  1119. def save_dict_items(pickler, obj):
  1120. logger.trace(pickler, "Di: <%s>", obj)
  1121. pickler.save_reduce(dicttype.items, (dicttype(obj),), obj=obj)
  1122. logger.trace(pickler, "# Di")
  1123. return (
  1124. ('keys', save_dict_keys),
  1125. ('values', save_dict_values),
  1126. ('items', save_dict_items)
  1127. )
  1128. for __dicttype in (
  1129. dict,
  1130. OrderedDict
  1131. ):
  1132. __obj = __dicttype()
  1133. for __funcname, __savefunc in save_dict_view(__dicttype):
  1134. __tview = type(getattr(__obj, __funcname)())
  1135. if __tview not in Pickler.dispatch:
  1136. Pickler.dispatch[__tview] = __savefunc
  1137. del __dicttype, __obj, __funcname, __tview, __savefunc
  1138. @register(ClassType)
  1139. def save_classobj(pickler, obj): #FIXME: enable pickler._byref
  1140. if not _locate_function(obj, pickler):
  1141. logger.trace(pickler, "C1: %s", obj)
  1142. pickler.save_reduce(ClassType, (obj.__name__, obj.__bases__,
  1143. obj.__dict__), obj=obj)
  1144. #XXX: or obj.__dict__.copy()), obj=obj) ?
  1145. logger.trace(pickler, "# C1")
  1146. else:
  1147. logger.trace(pickler, "C2: %s", obj)
  1148. name = getattr(obj, '__qualname__', getattr(obj, '__name__', None))
  1149. StockPickler.save_global(pickler, obj, name=name)
  1150. logger.trace(pickler, "# C2")
  1151. return
  1152. @register(typing._GenericAlias)
  1153. def save_generic_alias(pickler, obj):
  1154. args = obj.__args__
  1155. if type(obj.__reduce__()) is str:
  1156. logger.trace(pickler, "Ga0: %s", obj)
  1157. StockPickler.save_global(pickler, obj, name=obj.__reduce__())
  1158. logger.trace(pickler, "# Ga0")
  1159. elif obj.__origin__ is tuple and (not args or args == ((),)):
  1160. logger.trace(pickler, "Ga1: %s", obj)
  1161. pickler.save_reduce(_create_typing_tuple, (args,), obj=obj)
  1162. logger.trace(pickler, "# Ga1")
  1163. else:
  1164. logger.trace(pickler, "Ga2: %s", obj)
  1165. StockPickler.save_reduce(pickler, *obj.__reduce__(), obj=obj)
  1166. logger.trace(pickler, "# Ga2")
  1167. return
  1168. @register(LockType)
  1169. def save_lock(pickler, obj):
  1170. logger.trace(pickler, "Lo: %s", obj)
  1171. pickler.save_reduce(_create_lock, (obj.locked(),), obj=obj)
  1172. logger.trace(pickler, "# Lo")
  1173. return
  1174. @register(RLockType)
  1175. def save_rlock(pickler, obj):
  1176. logger.trace(pickler, "RL: %s", obj)
  1177. r = obj.__repr__() # don't use _release_save as it unlocks the lock
  1178. count = int(r.split('count=')[1].split()[0].rstrip('>'))
  1179. owner = int(r.split('owner=')[1].split()[0])
  1180. pickler.save_reduce(_create_rlock, (count,owner,), obj=obj)
  1181. logger.trace(pickler, "# RL")
  1182. return
  1183. #@register(SocketType) #FIXME: causes multiprocess test_pickling FAIL
  1184. def save_socket(pickler, obj):
  1185. logger.trace(pickler, "So: %s", obj)
  1186. pickler.save_reduce(*reduce_socket(obj))
  1187. logger.trace(pickler, "# So")
  1188. return
  1189. def _save_file(pickler, obj, open_):
  1190. if obj.closed:
  1191. position = 0
  1192. else:
  1193. obj.flush()
  1194. if obj in (sys.__stdout__, sys.__stderr__, sys.__stdin__):
  1195. position = -1
  1196. else:
  1197. position = obj.tell()
  1198. if is_dill(pickler, child=True) and pickler._fmode == FILE_FMODE:
  1199. f = open_(obj.name, "r")
  1200. fdata = f.read()
  1201. f.close()
  1202. else:
  1203. fdata = ""
  1204. if is_dill(pickler, child=True):
  1205. strictio = pickler._strictio
  1206. fmode = pickler._fmode
  1207. else:
  1208. strictio = False
  1209. fmode = 0 # HANDLE_FMODE
  1210. pickler.save_reduce(_create_filehandle, (obj.name, obj.mode, position,
  1211. obj.closed, open_, strictio,
  1212. fmode, fdata), obj=obj)
  1213. return
  1214. @register(FileType) #XXX: in 3.x has buffer=0, needs different _create?
  1215. @register(BufferedRandomType)
  1216. @register(BufferedReaderType)
  1217. @register(BufferedWriterType)
  1218. @register(TextWrapperType)
  1219. def save_file(pickler, obj):
  1220. logger.trace(pickler, "Fi: %s", obj)
  1221. f = _save_file(pickler, obj, open)
  1222. logger.trace(pickler, "# Fi")
  1223. return f
  1224. if PyTextWrapperType:
  1225. @register(PyBufferedRandomType)
  1226. @register(PyBufferedReaderType)
  1227. @register(PyBufferedWriterType)
  1228. @register(PyTextWrapperType)
  1229. def save_file(pickler, obj):
  1230. logger.trace(pickler, "Fi: %s", obj)
  1231. f = _save_file(pickler, obj, _open)
  1232. logger.trace(pickler, "# Fi")
  1233. return f
  1234. # The following two functions are based on 'saveCStringIoInput'
  1235. # and 'saveCStringIoOutput' from spickle
  1236. # Copyright (c) 2011 by science+computing ag
  1237. # License: http://www.apache.org/licenses/LICENSE-2.0
  1238. if InputType:
  1239. @register(InputType)
  1240. def save_stringi(pickler, obj):
  1241. logger.trace(pickler, "Io: %s", obj)
  1242. if obj.closed:
  1243. value = ''; position = 0
  1244. else:
  1245. value = obj.getvalue(); position = obj.tell()
  1246. pickler.save_reduce(_create_stringi, (value, position, \
  1247. obj.closed), obj=obj)
  1248. logger.trace(pickler, "# Io")
  1249. return
  1250. @register(OutputType)
  1251. def save_stringo(pickler, obj):
  1252. logger.trace(pickler, "Io: %s", obj)
  1253. if obj.closed:
  1254. value = ''; position = 0
  1255. else:
  1256. value = obj.getvalue(); position = obj.tell()
  1257. pickler.save_reduce(_create_stringo, (value, position, \
  1258. obj.closed), obj=obj)
  1259. logger.trace(pickler, "# Io")
  1260. return
  1261. if LRUCacheType is not None:
  1262. from functools import lru_cache
  1263. @register(LRUCacheType)
  1264. def save_lru_cache(pickler, obj):
  1265. logger.trace(pickler, "LRU: %s", obj)
  1266. if OLD39:
  1267. kwargs = obj.cache_info()
  1268. args = (kwargs.maxsize,)
  1269. else:
  1270. kwargs = obj.cache_parameters()
  1271. args = (kwargs['maxsize'], kwargs['typed'])
  1272. if args != lru_cache.__defaults__:
  1273. wrapper = Reduce(lru_cache, args, is_callable=True)
  1274. else:
  1275. wrapper = lru_cache
  1276. pickler.save_reduce(wrapper, (obj.__wrapped__,), obj=obj)
  1277. logger.trace(pickler, "# LRU")
  1278. return
  1279. @register(SuperType)
  1280. def save_super(pickler, obj):
  1281. logger.trace(pickler, "Su: %s", obj)
  1282. pickler.save_reduce(super, (obj.__thisclass__, obj.__self__), obj=obj)
  1283. logger.trace(pickler, "# Su")
  1284. return
  1285. if IS_PYPY:
  1286. @register(MethodType)
  1287. def save_instancemethod0(pickler, obj):
  1288. code = getattr(obj.__func__, '__code__', None)
  1289. if code is not None and type(code) is not CodeType \
  1290. and getattr(obj.__self__, obj.__name__) == obj:
  1291. # Some PyPy builtin functions have no module name
  1292. logger.trace(pickler, "Me2: %s", obj)
  1293. # TODO: verify that this works for all PyPy builtin methods
  1294. pickler.save_reduce(getattr, (obj.__self__, obj.__name__), obj=obj)
  1295. logger.trace(pickler, "# Me2")
  1296. return
  1297. logger.trace(pickler, "Me1: %s", obj)
  1298. pickler.save_reduce(MethodType, (obj.__func__, obj.__self__), obj=obj)
  1299. logger.trace(pickler, "# Me1")
  1300. return
  1301. else:
  1302. @register(MethodType)
  1303. def save_instancemethod0(pickler, obj):
  1304. logger.trace(pickler, "Me1: %s", obj)
  1305. pickler.save_reduce(MethodType, (obj.__func__, obj.__self__), obj=obj)
  1306. logger.trace(pickler, "# Me1")
  1307. return
  1308. if not IS_PYPY:
  1309. @register(MemberDescriptorType)
  1310. @register(GetSetDescriptorType)
  1311. @register(MethodDescriptorType)
  1312. @register(WrapperDescriptorType)
  1313. @register(ClassMethodDescriptorType)
  1314. def save_wrapper_descriptor(pickler, obj):
  1315. logger.trace(pickler, "Wr: %s", obj)
  1316. pickler.save_reduce(_getattr, (obj.__objclass__, obj.__name__,
  1317. obj.__repr__()), obj=obj)
  1318. logger.trace(pickler, "# Wr")
  1319. return
  1320. else:
  1321. @register(MemberDescriptorType)
  1322. @register(GetSetDescriptorType)
  1323. def save_wrapper_descriptor(pickler, obj):
  1324. logger.trace(pickler, "Wr: %s", obj)
  1325. pickler.save_reduce(_getattr, (obj.__objclass__, obj.__name__,
  1326. obj.__repr__()), obj=obj)
  1327. logger.trace(pickler, "# Wr")
  1328. return
  1329. @register(CellType)
  1330. def save_cell(pickler, obj):
  1331. try:
  1332. f = obj.cell_contents
  1333. except ValueError: # cell is empty
  1334. logger.trace(pickler, "Ce3: %s", obj)
  1335. # _shims._CELL_EMPTY is defined in _shims.py to support PyPy 2.7.
  1336. # It unpickles to a sentinel object _dill._CELL_EMPTY, also created in
  1337. # _shims.py. This object is not present in Python 3 because the cell's
  1338. # contents can be deleted in newer versions of Python. The reduce object
  1339. # will instead unpickle to None if unpickled in Python 3.
  1340. # When breaking changes are made to dill, (_shims._CELL_EMPTY,) can
  1341. # be replaced by () OR the delattr function can be removed repending on
  1342. # whichever is more convienient.
  1343. pickler.save_reduce(_create_cell, (_shims._CELL_EMPTY,), obj=obj)
  1344. # Call the function _delattr on the cell's cell_contents attribute
  1345. # The result of this function call will be None
  1346. pickler.save_reduce(_shims._delattr, (obj, 'cell_contents'))
  1347. # pop None created by calling _delattr off stack
  1348. pickler.write(POP)
  1349. logger.trace(pickler, "# Ce3")
  1350. return
  1351. if is_dill(pickler, child=True):
  1352. if id(f) in pickler._postproc:
  1353. # Already seen. Add to its postprocessing.
  1354. postproc = pickler._postproc[id(f)]
  1355. else:
  1356. # Haven't seen it. Add to the highest possible object and set its
  1357. # value as late as possible to prevent cycle.
  1358. postproc = next(iter(pickler._postproc.values()), None)
  1359. if postproc is not None:
  1360. logger.trace(pickler, "Ce2: %s", obj)
  1361. # _CELL_REF is defined in _shims.py to support older versions of
  1362. # dill. When breaking changes are made to dill, (_CELL_REF,) can
  1363. # be replaced by ()
  1364. pickler.save_reduce(_create_cell, (_CELL_REF,), obj=obj)
  1365. postproc.append((_shims._setattr, (obj, 'cell_contents', f)))
  1366. logger.trace(pickler, "# Ce2")
  1367. return
  1368. logger.trace(pickler, "Ce1: %s", obj)
  1369. pickler.save_reduce(_create_cell, (f,), obj=obj)
  1370. logger.trace(pickler, "# Ce1")
  1371. return
  1372. if MAPPING_PROXY_TRICK:
  1373. @register(DictProxyType)
  1374. def save_dictproxy(pickler, obj):
  1375. logger.trace(pickler, "Mp: %s", _repr_dict(obj)) # obj
  1376. mapping = obj | _dictproxy_helper_instance
  1377. pickler.save_reduce(DictProxyType, (mapping,), obj=obj)
  1378. logger.trace(pickler, "# Mp")
  1379. return
  1380. else:
  1381. @register(DictProxyType)
  1382. def save_dictproxy(pickler, obj):
  1383. logger.trace(pickler, "Mp: %s", _repr_dict(obj)) # obj
  1384. pickler.save_reduce(DictProxyType, (obj.copy(),), obj=obj)
  1385. logger.trace(pickler, "# Mp")
  1386. return
  1387. @register(SliceType)
  1388. def save_slice(pickler, obj):
  1389. logger.trace(pickler, "Sl: %s", obj)
  1390. pickler.save_reduce(slice, (obj.start, obj.stop, obj.step), obj=obj)
  1391. logger.trace(pickler, "# Sl")
  1392. return
  1393. @register(XRangeType)
  1394. @register(EllipsisType)
  1395. @register(NotImplementedType)
  1396. def save_singleton(pickler, obj):
  1397. logger.trace(pickler, "Si: %s", obj)
  1398. pickler.save_reduce(_eval_repr, (obj.__repr__(),), obj=obj)
  1399. logger.trace(pickler, "# Si")
  1400. return
  1401. def _proxy_helper(obj): # a dead proxy returns a reference to None
  1402. """get memory address of proxy's reference object"""
  1403. _repr = repr(obj)
  1404. try: _str = str(obj)
  1405. except ReferenceError: # it's a dead proxy
  1406. return id(None)
  1407. if _str == _repr: return id(obj) # it's a repr
  1408. try: # either way, it's a proxy from here
  1409. address = int(_str.rstrip('>').split(' at ')[-1], base=16)
  1410. except ValueError: # special case: proxy of a 'type'
  1411. if not IS_PYPY:
  1412. address = int(_repr.rstrip('>').split(' at ')[-1], base=16)
  1413. else:
  1414. objects = iter(gc.get_objects())
  1415. for _obj in objects:
  1416. if repr(_obj) == _str: return id(_obj)
  1417. # all bad below... nothing found so throw ReferenceError
  1418. msg = "Cannot reference object for proxy at '%s'" % id(obj)
  1419. raise ReferenceError(msg)
  1420. return address
  1421. def _locate_object(address, module=None):
  1422. """get object located at the given memory address (inverse of id(obj))"""
  1423. special = [None, True, False] #XXX: more...?
  1424. for obj in special:
  1425. if address == id(obj): return obj
  1426. if module:
  1427. objects = iter(module.__dict__.values())
  1428. else: objects = iter(gc.get_objects())
  1429. for obj in objects:
  1430. if address == id(obj): return obj
  1431. # all bad below... nothing found so throw ReferenceError or TypeError
  1432. try: address = hex(address)
  1433. except TypeError:
  1434. raise TypeError("'%s' is not a valid memory address" % str(address))
  1435. raise ReferenceError("Cannot reference object at '%s'" % address)
  1436. @register(ReferenceType)
  1437. def save_weakref(pickler, obj):
  1438. refobj = obj()
  1439. logger.trace(pickler, "R1: %s", obj)
  1440. #refobj = ctypes.pythonapi.PyWeakref_GetObject(obj) # dead returns "None"
  1441. pickler.save_reduce(_create_weakref, (refobj,), obj=obj)
  1442. logger.trace(pickler, "# R1")
  1443. return
  1444. @register(ProxyType)
  1445. @register(CallableProxyType)
  1446. def save_weakproxy(pickler, obj):
  1447. # Must do string substitution here and use %r to avoid ReferenceError.
  1448. logger.trace(pickler, "R2: %r" % obj)
  1449. refobj = _locate_object(_proxy_helper(obj))
  1450. pickler.save_reduce(_create_weakproxy, (refobj, callable(obj)), obj=obj)
  1451. logger.trace(pickler, "# R2")
  1452. return
  1453. def _is_builtin_module(module):
  1454. if not hasattr(module, "__file__"): return True
  1455. if module.__file__ is None: return False
  1456. # If a module file name starts with prefix, it should be a builtin
  1457. # module, so should always be pickled as a reference.
  1458. names = ["base_prefix", "base_exec_prefix", "exec_prefix", "prefix", "real_prefix"]
  1459. rp = os.path.realpath
  1460. # See https://github.com/uqfoundation/dill/issues/566
  1461. return (
  1462. any(
  1463. module.__file__.startswith(getattr(sys, name))
  1464. or rp(module.__file__).startswith(rp(getattr(sys, name)))
  1465. for name in names
  1466. if hasattr(sys, name)
  1467. )
  1468. or module.__file__.endswith(EXTENSION_SUFFIXES)
  1469. or 'site-packages' in module.__file__
  1470. )
  1471. def _is_imported_module(module):
  1472. return getattr(module, '__loader__', None) is not None or module in sys.modules.values()
  1473. @register(ModuleType)
  1474. def save_module(pickler, obj):
  1475. if False: #_use_diff:
  1476. if obj.__name__.split('.', 1)[0] != "dill":
  1477. try:
  1478. changed = diff.whats_changed(obj, seen=pickler._diff_cache)[0]
  1479. except RuntimeError: # not memorised module, probably part of dill
  1480. pass
  1481. else:
  1482. logger.trace(pickler, "M2: %s with diff", obj)
  1483. logger.info("Diff: %s", changed.keys())
  1484. pickler.save_reduce(_import_module, (obj.__name__,), obj=obj,
  1485. state=changed)
  1486. logger.trace(pickler, "# M2")
  1487. return
  1488. logger.trace(pickler, "M1: %s", obj)
  1489. pickler.save_reduce(_import_module, (obj.__name__,), obj=obj)
  1490. logger.trace(pickler, "# M1")
  1491. else:
  1492. builtin_mod = _is_builtin_module(obj)
  1493. is_session_main = is_dill(pickler, child=True) and obj is pickler._main
  1494. if (obj.__name__ not in ("builtins", "dill", "dill._dill") and not builtin_mod
  1495. or is_session_main):
  1496. logger.trace(pickler, "M1: %s", obj)
  1497. # Hack for handling module-type objects in load_module().
  1498. mod_name = obj.__name__ if _is_imported_module(obj) else '__runtime__.%s' % obj.__name__
  1499. # Second references are saved as __builtin__.__main__ in save_module_dict().
  1500. main_dict = obj.__dict__.copy()
  1501. for item in ('__builtins__', '__loader__'):
  1502. main_dict.pop(item, None)
  1503. for item in IPYTHON_SINGLETONS: #pragma: no cover
  1504. if getattr(main_dict.get(item), '__module__', '').startswith('IPython'):
  1505. del main_dict[item]
  1506. pickler.save_reduce(_import_module, (mod_name,), obj=obj, state=main_dict)
  1507. logger.trace(pickler, "# M1")
  1508. elif obj.__name__ == "dill._dill":
  1509. logger.trace(pickler, "M2: %s", obj)
  1510. pickler.save_global(obj, name="_dill")
  1511. logger.trace(pickler, "# M2")
  1512. else:
  1513. logger.trace(pickler, "M2: %s", obj)
  1514. pickler.save_reduce(_import_module, (obj.__name__,), obj=obj)
  1515. logger.trace(pickler, "# M2")
  1516. return
  1517. # The following function is based on '_extract_class_dict' from 'cloudpickle'
  1518. # Copyright (c) 2012, Regents of the University of California.
  1519. # Copyright (c) 2009 `PiCloud, Inc. <http://www.picloud.com>`_.
  1520. # License: https://github.com/cloudpipe/cloudpickle/blob/master/LICENSE
  1521. def _get_typedict_type(cls, clsdict, attrs, postproc_list):
  1522. """Retrieve a copy of the dict of a class without the inherited methods"""
  1523. if len(cls.__bases__) == 1:
  1524. inherited_dict = cls.__bases__[0].__dict__
  1525. else:
  1526. inherited_dict = {}
  1527. for base in reversed(cls.__bases__):
  1528. inherited_dict.update(base.__dict__)
  1529. to_remove = []
  1530. for name, value in dict.items(clsdict):
  1531. try:
  1532. base_value = inherited_dict[name]
  1533. if value is base_value:
  1534. to_remove.append(name)
  1535. except KeyError:
  1536. pass
  1537. for name in to_remove:
  1538. dict.pop(clsdict, name)
  1539. if issubclass(type(cls), type):
  1540. clsdict.pop('__dict__', None)
  1541. clsdict.pop('__weakref__', None)
  1542. # clsdict.pop('__prepare__', None)
  1543. return clsdict, attrs
  1544. def _get_typedict_abc(obj, _dict, attrs, postproc_list):
  1545. if hasattr(abc, '_get_dump'):
  1546. (registry, _, _, _) = abc._get_dump(obj)
  1547. register = obj.register
  1548. postproc_list.extend((register, (reg(),)) for reg in registry)
  1549. elif hasattr(obj, '_abc_registry'):
  1550. registry = obj._abc_registry
  1551. register = obj.register
  1552. postproc_list.extend((register, (reg,)) for reg in registry)
  1553. else:
  1554. raise PicklingError("Cannot find registry of ABC %s", obj)
  1555. if '_abc_registry' in _dict:
  1556. _dict.pop('_abc_registry', None)
  1557. _dict.pop('_abc_cache', None)
  1558. _dict.pop('_abc_negative_cache', None)
  1559. # _dict.pop('_abc_negative_cache_version', None)
  1560. else:
  1561. _dict.pop('_abc_impl', None)
  1562. return _dict, attrs
  1563. @register(TypeType)
  1564. def save_type(pickler, obj, postproc_list=None):
  1565. if obj in _typemap:
  1566. logger.trace(pickler, "T1: %s", obj)
  1567. # if obj in _incedental_types:
  1568. # warnings.warn('Type %r may only exist on this implementation of Python and cannot be unpickled in other implementations.' % (obj,), PicklingWarning)
  1569. pickler.save_reduce(_load_type, (_typemap[obj],), obj=obj)
  1570. logger.trace(pickler, "# T1")
  1571. elif obj.__bases__ == (tuple,) and all([hasattr(obj, attr) for attr in ('_fields','_asdict','_make','_replace')]):
  1572. # special case: namedtuples
  1573. logger.trace(pickler, "T6: %s", obj)
  1574. obj_name = getattr(obj, '__qualname__', getattr(obj, '__name__', None))
  1575. if obj.__name__ != obj_name:
  1576. if postproc_list is None:
  1577. postproc_list = []
  1578. postproc_list.append((setattr, (obj, '__qualname__', obj_name)))
  1579. if not obj._field_defaults:
  1580. _save_with_postproc(pickler, (_create_namedtuple, (obj.__name__, obj._fields, obj.__module__)), obj=obj, postproc_list=postproc_list)
  1581. else:
  1582. defaults = [obj._field_defaults[field] for field in obj._fields if field in obj._field_defaults]
  1583. _save_with_postproc(pickler, (_create_namedtuple, (obj.__name__, obj._fields, obj.__module__, defaults)), obj=obj, postproc_list=postproc_list)
  1584. logger.trace(pickler, "# T6")
  1585. return
  1586. # special cases: NoneType, NotImplementedType, EllipsisType, EnumMeta
  1587. elif obj is type(None):
  1588. logger.trace(pickler, "T7: %s", obj)
  1589. #XXX: pickler.save_reduce(type, (None,), obj=obj)
  1590. pickler.write(GLOBAL + b'__builtin__\nNoneType\n')
  1591. logger.trace(pickler, "# T7")
  1592. elif obj is NotImplementedType:
  1593. logger.trace(pickler, "T7: %s", obj)
  1594. pickler.save_reduce(type, (NotImplemented,), obj=obj)
  1595. logger.trace(pickler, "# T7")
  1596. elif obj is EllipsisType:
  1597. logger.trace(pickler, "T7: %s", obj)
  1598. pickler.save_reduce(type, (Ellipsis,), obj=obj)
  1599. logger.trace(pickler, "# T7")
  1600. elif obj is EnumMeta:
  1601. logger.trace(pickler, "T7: %s", obj)
  1602. pickler.write(GLOBAL + b'enum\nEnumMeta\n')
  1603. logger.trace(pickler, "# T7")
  1604. else:
  1605. _byref = getattr(pickler, '_byref', None)
  1606. obj_recursive = id(obj) in getattr(pickler, '_postproc', ())
  1607. incorrectly_named = not _locate_function(obj, pickler)
  1608. if not _byref and not obj_recursive and incorrectly_named: # not a function, but the name was held over
  1609. if postproc_list is None:
  1610. postproc_list = []
  1611. # thanks to Tom Stepleton pointing out pickler._session unneeded
  1612. logger.trace(pickler, "T2: %s", obj)
  1613. _dict, attrs = _get_typedict_type(obj, obj.__dict__.copy(), None, postproc_list) # copy dict proxy to a dict
  1614. #print (_dict)
  1615. #print ("%s\n%s" % (type(obj), obj.__name__))
  1616. #print ("%s\n%s" % (obj.__bases__, obj.__dict__))
  1617. slots = _dict.get('__slots__', ())
  1618. if type(slots) == str:
  1619. # __slots__ accepts a single string
  1620. slots = (slots,)
  1621. for name in slots:
  1622. _dict.pop(name, None)
  1623. if isinstance(obj, abc.ABCMeta):
  1624. logger.trace(pickler, "ABC: %s", obj)
  1625. _dict, attrs = _get_typedict_abc(obj, _dict, attrs, postproc_list)
  1626. logger.trace(pickler, "# ABC")
  1627. qualname = getattr(obj, '__qualname__', None)
  1628. if attrs is not None:
  1629. for k, v in attrs.items():
  1630. postproc_list.append((setattr, (obj, k, v)))
  1631. # TODO: Consider using the state argument to save_reduce?
  1632. if qualname is not None:
  1633. postproc_list.append((setattr, (obj, '__qualname__', qualname)))
  1634. if not hasattr(obj, '__orig_bases__'):
  1635. _save_with_postproc(pickler, (_create_type, (
  1636. type(obj), obj.__name__, obj.__bases__, _dict
  1637. )), obj=obj, postproc_list=postproc_list)
  1638. else:
  1639. # This case will always work, but might be overkill.
  1640. _metadict = {
  1641. 'metaclass': type(obj)
  1642. }
  1643. if _dict:
  1644. _dict_update = PartialType(_setitems, source=_dict)
  1645. else:
  1646. _dict_update = None
  1647. _save_with_postproc(pickler, (new_class, (
  1648. obj.__name__, obj.__orig_bases__, _metadict, _dict_update
  1649. )), obj=obj, postproc_list=postproc_list)
  1650. logger.trace(pickler, "# T2")
  1651. else:
  1652. obj_name = getattr(obj, '__qualname__', getattr(obj, '__name__', None))
  1653. logger.trace(pickler, "T4: %s", obj)
  1654. if incorrectly_named:
  1655. warnings.warn(
  1656. "Cannot locate reference to %r." % (obj,),
  1657. PicklingWarning,
  1658. stacklevel=3,
  1659. )
  1660. if obj_recursive:
  1661. warnings.warn(
  1662. "Cannot pickle %r: %s.%s has recursive self-references that "
  1663. "trigger a RecursionError." % (obj, obj.__module__, obj_name),
  1664. PicklingWarning,
  1665. stacklevel=3,
  1666. )
  1667. #print (obj.__dict__)
  1668. #print ("%s\n%s" % (type(obj), obj.__name__))
  1669. #print ("%s\n%s" % (obj.__bases__, obj.__dict__))
  1670. StockPickler.save_global(pickler, obj, name=obj_name)
  1671. logger.trace(pickler, "# T4")
  1672. return
  1673. @register(property)
  1674. @register(abc.abstractproperty)
  1675. def save_property(pickler, obj):
  1676. logger.trace(pickler, "Pr: %s", obj)
  1677. pickler.save_reduce(type(obj), (obj.fget, obj.fset, obj.fdel, obj.__doc__),
  1678. obj=obj)
  1679. logger.trace(pickler, "# Pr")
  1680. @register(staticmethod)
  1681. @register(classmethod)
  1682. @register(abc.abstractstaticmethod)
  1683. @register(abc.abstractclassmethod)
  1684. def save_classmethod(pickler, obj):
  1685. logger.trace(pickler, "Cm: %s", obj)
  1686. orig_func = obj.__func__
  1687. # if type(obj.__dict__) is dict:
  1688. # if obj.__dict__:
  1689. # state = obj.__dict__
  1690. # else:
  1691. # state = None
  1692. # else:
  1693. # state = (None, {'__dict__', obj.__dict__})
  1694. pickler.save_reduce(type(obj), (orig_func,), obj=obj)
  1695. logger.trace(pickler, "# Cm")
  1696. @register(FunctionType)
  1697. def save_function(pickler, obj):
  1698. if not _locate_function(obj, pickler):
  1699. if type(obj.__code__) is not CodeType:
  1700. # Some PyPy builtin functions have no module name, and thus are not
  1701. # able to be located
  1702. module_name = getattr(obj, '__module__', None)
  1703. if module_name is None:
  1704. module_name = __builtin__.__name__
  1705. module = _import_module(module_name, safe=True)
  1706. _pypy_builtin = False
  1707. try:
  1708. found, _ = _getattribute(module, obj.__qualname__)
  1709. if getattr(found, '__func__', None) is obj:
  1710. _pypy_builtin = True
  1711. except AttributeError:
  1712. pass
  1713. if _pypy_builtin:
  1714. logger.trace(pickler, "F3: %s", obj)
  1715. pickler.save_reduce(getattr, (found, '__func__'), obj=obj)
  1716. logger.trace(pickler, "# F3")
  1717. return
  1718. logger.trace(pickler, "F1: %s", obj)
  1719. _recurse = getattr(pickler, '_recurse', None)
  1720. _postproc = getattr(pickler, '_postproc', None)
  1721. _main_modified = getattr(pickler, '_main_modified', None)
  1722. _original_main = getattr(pickler, '_original_main', __builtin__)#'None'
  1723. postproc_list = []
  1724. if _recurse:
  1725. # recurse to get all globals referred to by obj
  1726. from .detect import globalvars
  1727. globs_copy = globalvars(obj, recurse=True, builtin=True)
  1728. # Add the name of the module to the globs dictionary to prevent
  1729. # the duplication of the dictionary. Pickle the unpopulated
  1730. # globals dictionary and set the remaining items after the function
  1731. # is created to correctly handle recursion.
  1732. globs = {'__name__': obj.__module__}
  1733. else:
  1734. globs_copy = obj.__globals__
  1735. # If the globals is the __dict__ from the module being saved as a
  1736. # session, substitute it by the dictionary being actually saved.
  1737. if _main_modified and globs_copy is _original_main.__dict__:
  1738. globs_copy = getattr(pickler, '_main', _original_main).__dict__
  1739. globs = globs_copy
  1740. # If the globals is a module __dict__, do not save it in the pickle.
  1741. elif globs_copy is not None and obj.__module__ is not None and \
  1742. getattr(_import_module(obj.__module__, True), '__dict__', None) is globs_copy:
  1743. globs = globs_copy
  1744. else:
  1745. globs = {'__name__': obj.__module__}
  1746. if globs_copy is not None and globs is not globs_copy:
  1747. # In the case that the globals are copied, we need to ensure that
  1748. # the globals dictionary is updated when all objects in the
  1749. # dictionary are already created.
  1750. glob_ids = {id(g) for g in globs_copy.values()}
  1751. for stack_element in _postproc:
  1752. if stack_element in glob_ids:
  1753. _postproc[stack_element].append((_setitems, (globs, globs_copy)))
  1754. break
  1755. else:
  1756. postproc_list.append((_setitems, (globs, globs_copy)))
  1757. closure = obj.__closure__
  1758. state_dict = {}
  1759. for fattrname in ('__doc__', '__kwdefaults__', '__annotations__'):
  1760. fattr = getattr(obj, fattrname, None)
  1761. if fattr is not None:
  1762. state_dict[fattrname] = fattr
  1763. if obj.__qualname__ != obj.__name__:
  1764. state_dict['__qualname__'] = obj.__qualname__
  1765. if '__name__' not in globs or obj.__module__ != globs['__name__']:
  1766. state_dict['__module__'] = obj.__module__
  1767. state = obj.__dict__
  1768. if type(state) is not dict:
  1769. state_dict['__dict__'] = state
  1770. state = None
  1771. if state_dict:
  1772. state = state, state_dict
  1773. _save_with_postproc(pickler, (_create_function, (
  1774. obj.__code__, globs, obj.__name__, obj.__defaults__,
  1775. closure
  1776. ), state), obj=obj, postproc_list=postproc_list)
  1777. # Lift closure cell update to earliest function (#458)
  1778. if _postproc:
  1779. topmost_postproc = next(iter(_postproc.values()), None)
  1780. if closure and topmost_postproc:
  1781. for cell in closure:
  1782. possible_postproc = (setattr, (cell, 'cell_contents', obj))
  1783. try:
  1784. topmost_postproc.remove(possible_postproc)
  1785. except ValueError:
  1786. continue
  1787. # Change the value of the cell
  1788. pickler.save_reduce(*possible_postproc)
  1789. # pop None created by calling preprocessing step off stack
  1790. pickler.write(POP)
  1791. logger.trace(pickler, "# F1")
  1792. else:
  1793. logger.trace(pickler, "F2: %s", obj)
  1794. name = getattr(obj, '__qualname__', getattr(obj, '__name__', None))
  1795. StockPickler.save_global(pickler, obj, name=name)
  1796. logger.trace(pickler, "# F2")
  1797. return
  1798. if HAS_CTYPES and hasattr(ctypes, 'pythonapi'):
  1799. _PyCapsule_New = ctypes.pythonapi.PyCapsule_New
  1800. _PyCapsule_New.argtypes = (ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p)
  1801. _PyCapsule_New.restype = ctypes.py_object
  1802. _PyCapsule_GetPointer = ctypes.pythonapi.PyCapsule_GetPointer
  1803. _PyCapsule_GetPointer.argtypes = (ctypes.py_object, ctypes.c_char_p)
  1804. _PyCapsule_GetPointer.restype = ctypes.c_void_p
  1805. _PyCapsule_GetDestructor = ctypes.pythonapi.PyCapsule_GetDestructor
  1806. _PyCapsule_GetDestructor.argtypes = (ctypes.py_object,)
  1807. _PyCapsule_GetDestructor.restype = ctypes.c_void_p
  1808. _PyCapsule_GetContext = ctypes.pythonapi.PyCapsule_GetContext
  1809. _PyCapsule_GetContext.argtypes = (ctypes.py_object,)
  1810. _PyCapsule_GetContext.restype = ctypes.c_void_p
  1811. _PyCapsule_GetName = ctypes.pythonapi.PyCapsule_GetName
  1812. _PyCapsule_GetName.argtypes = (ctypes.py_object,)
  1813. _PyCapsule_GetName.restype = ctypes.c_char_p
  1814. _PyCapsule_IsValid = ctypes.pythonapi.PyCapsule_IsValid
  1815. _PyCapsule_IsValid.argtypes = (ctypes.py_object, ctypes.c_char_p)
  1816. _PyCapsule_IsValid.restype = ctypes.c_bool
  1817. _PyCapsule_SetContext = ctypes.pythonapi.PyCapsule_SetContext
  1818. _PyCapsule_SetContext.argtypes = (ctypes.py_object, ctypes.c_void_p)
  1819. _PyCapsule_SetDestructor = ctypes.pythonapi.PyCapsule_SetDestructor
  1820. _PyCapsule_SetDestructor.argtypes = (ctypes.py_object, ctypes.c_void_p)
  1821. _PyCapsule_SetName = ctypes.pythonapi.PyCapsule_SetName
  1822. _PyCapsule_SetName.argtypes = (ctypes.py_object, ctypes.c_char_p)
  1823. _PyCapsule_SetPointer = ctypes.pythonapi.PyCapsule_SetPointer
  1824. _PyCapsule_SetPointer.argtypes = (ctypes.py_object, ctypes.c_void_p)
  1825. _testcapsule = _PyCapsule_New(
  1826. ctypes.cast(_PyCapsule_New, ctypes.c_void_p),
  1827. ctypes.create_string_buffer(b'dill._dill._testcapsule'),
  1828. None
  1829. )
  1830. PyCapsuleType = type(_testcapsule)
  1831. @register(PyCapsuleType)
  1832. def save_capsule(pickler, obj):
  1833. logger.trace(pickler, "Cap: %s", obj)
  1834. name = _PyCapsule_GetName(obj)
  1835. #warnings.warn('Pickling a PyCapsule (%s) does not pickle any C data structures and could cause segmentation faults or other memory errors when unpickling.' % (name,), PicklingWarning)
  1836. pointer = _PyCapsule_GetPointer(obj, name)
  1837. context = _PyCapsule_GetContext(obj)
  1838. destructor = _PyCapsule_GetDestructor(obj)
  1839. pickler.save_reduce(_create_capsule, (pointer, name, context, destructor), obj=obj)
  1840. logger.trace(pickler, "# Cap")
  1841. _incedental_reverse_typemap['PyCapsuleType'] = PyCapsuleType
  1842. _reverse_typemap['PyCapsuleType'] = PyCapsuleType
  1843. _incedental_types.add(PyCapsuleType)
  1844. else:
  1845. _testcapsule = None
  1846. #############################
  1847. # A quick fix for issue #500
  1848. # This should be removed when a better solution is found.
  1849. if hasattr(dataclasses, "_HAS_DEFAULT_FACTORY_CLASS"):
  1850. @register(dataclasses._HAS_DEFAULT_FACTORY_CLASS)
  1851. def save_dataclasses_HAS_DEFAULT_FACTORY_CLASS(pickler, obj):
  1852. logger.trace(pickler, "DcHDF: %s", obj)
  1853. pickler.write(GLOBAL + b"dataclasses\n_HAS_DEFAULT_FACTORY\n")
  1854. logger.trace(pickler, "# DcHDF")
  1855. if hasattr(dataclasses, "MISSING"):
  1856. @register(type(dataclasses.MISSING))
  1857. def save_dataclasses_MISSING_TYPE(pickler, obj):
  1858. logger.trace(pickler, "DcM: %s", obj)
  1859. pickler.write(GLOBAL + b"dataclasses\nMISSING\n")
  1860. logger.trace(pickler, "# DcM")
  1861. if hasattr(dataclasses, "KW_ONLY"):
  1862. @register(type(dataclasses.KW_ONLY))
  1863. def save_dataclasses_KW_ONLY_TYPE(pickler, obj):
  1864. logger.trace(pickler, "DcKWO: %s", obj)
  1865. pickler.write(GLOBAL + b"dataclasses\nKW_ONLY\n")
  1866. logger.trace(pickler, "# DcKWO")
  1867. if hasattr(dataclasses, "_FIELD_BASE"):
  1868. @register(dataclasses._FIELD_BASE)
  1869. def save_dataclasses_FIELD_BASE(pickler, obj):
  1870. logger.trace(pickler, "DcFB: %s", obj)
  1871. pickler.write(GLOBAL + b"dataclasses\n" + obj.name.encode() + b"\n")
  1872. logger.trace(pickler, "# DcFB")
  1873. #############################
  1874. # quick sanity checking
  1875. def pickles(obj,exact=False,safe=False,**kwds):
  1876. """
  1877. Quick check if object pickles with dill.
  1878. If *exact=True* then an equality test is done to check if the reconstructed
  1879. object matches the original object.
  1880. If *safe=True* then any exception will raised in copy signal that the
  1881. object is not picklable, otherwise only pickling errors will be trapped.
  1882. Additional keyword arguments are as :func:`dumps` and :func:`loads`.
  1883. """
  1884. if safe: exceptions = (Exception,) # RuntimeError, ValueError
  1885. else:
  1886. exceptions = (TypeError, AssertionError, NotImplementedError, PicklingError, UnpicklingError)
  1887. try:
  1888. pik = copy(obj, **kwds)
  1889. #FIXME: should check types match first, then check content if "exact"
  1890. try:
  1891. #FIXME: should be "(pik == obj).all()" for numpy comparison, though that'll fail if shapes differ
  1892. result = bool(pik.all() == obj.all())
  1893. except (AttributeError, TypeError):
  1894. warnings.filterwarnings('ignore') #FIXME: be specific
  1895. result = pik == obj
  1896. if warnings.filters: del warnings.filters[0]
  1897. if hasattr(result, 'toarray'): # for unusual types like sparse matrix
  1898. result = result.toarray().all()
  1899. if result: return True
  1900. if not exact:
  1901. result = type(pik) == type(obj)
  1902. if result: return result
  1903. # class instances might have been dumped with byref=False
  1904. return repr(type(pik)) == repr(type(obj)) #XXX: InstanceType?
  1905. return False
  1906. except exceptions:
  1907. return False
  1908. def check(obj, *args, **kwds):
  1909. """
  1910. Check pickling of an object across another process.
  1911. *python* is the path to the python interpreter (defaults to sys.executable)
  1912. Set *verbose=True* to print the unpickled object in the other process.
  1913. Additional keyword arguments are as :func:`dumps` and :func:`loads`.
  1914. """
  1915. # == undocumented ==
  1916. # python -- the string path or executable name of the selected python
  1917. # verbose -- if True, be verbose about printing warning messages
  1918. # all other args and kwds are passed to dill.dumps #FIXME: ignore on load
  1919. verbose = kwds.pop('verbose', False)
  1920. python = kwds.pop('python', None)
  1921. if python is None:
  1922. import sys
  1923. python = sys.executable
  1924. # type check
  1925. isinstance(python, str)
  1926. import subprocess
  1927. fail = True
  1928. try:
  1929. _obj = dumps(obj, *args, **kwds)
  1930. fail = False
  1931. finally:
  1932. if fail and verbose:
  1933. print("DUMP FAILED")
  1934. #FIXME: fails if python interpreter path contains spaces
  1935. # Use the following instead (which also processes the 'ignore' keyword):
  1936. # ignore = kwds.pop('ignore', None)
  1937. # unpickle = "dill.loads(%s, ignore=%s)"%(repr(_obj), repr(ignore))
  1938. # cmd = [python, "-c", "import dill; print(%s)"%unpickle]
  1939. # msg = "SUCCESS" if not subprocess.call(cmd) else "LOAD FAILED"
  1940. msg = "%s -c import dill; print(dill.loads(%s))" % (python, repr(_obj))
  1941. msg = "SUCCESS" if not subprocess.call(msg.split(None,2)) else "LOAD FAILED"
  1942. if verbose:
  1943. print(msg)
  1944. return
  1945. # use to protect against missing attributes
  1946. def is_dill(pickler, child=None):
  1947. "check the dill-ness of your pickler"
  1948. if child is False or not hasattr(pickler.__class__, 'mro'):
  1949. return 'dill' in pickler.__module__
  1950. return Pickler in pickler.__class__.mro()
  1951. def _extend():
  1952. """extend pickle with all of dill's registered types"""
  1953. # need to have pickle not choke on _main_module? use is_dill(pickler)
  1954. for t,func in Pickler.dispatch.items():
  1955. try:
  1956. StockPickler.dispatch[t] = func
  1957. except Exception: #TypeError, PicklingError, UnpicklingError
  1958. logger.trace(pickler, "skip: %s", t)
  1959. return
  1960. del diff, _use_diff, use_diff
  1961. # EOF