_dill.py 90 KB

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