_objects.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. #!/usr/bin/env python
  2. #
  3. # Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
  4. # Copyright (c) 2008-2016 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. all Python Standard Library objects (currently: CH 1-15 @ 2.7)
  10. and some other common objects (i.e. numpy.ndarray)
  11. """
  12. __all__ = ['registered','failures','succeeds']
  13. # helper imports
  14. import warnings; warnings.filterwarnings("ignore", category=DeprecationWarning)
  15. import sys
  16. import queue as Queue
  17. #import dbm as anydbm #XXX: delete foo
  18. from io import BytesIO as StringIO
  19. import re
  20. import array
  21. import collections
  22. import codecs
  23. import struct
  24. import dataclasses
  25. import datetime
  26. import calendar
  27. import weakref
  28. import pprint
  29. import decimal
  30. import numbers
  31. import functools
  32. import itertools
  33. import operator
  34. import tempfile
  35. import shelve
  36. import zlib
  37. import gzip
  38. import zipfile
  39. import tarfile
  40. import csv
  41. import hashlib
  42. import hmac
  43. import os
  44. import logging
  45. import logging.handlers
  46. import optparse
  47. #import __hello__
  48. import threading
  49. import socket
  50. import contextlib
  51. import contextvars
  52. try:
  53. import bz2
  54. import sqlite3
  55. import dbm.ndbm as dbm
  56. HAS_ALL = True
  57. except ImportError: # Ubuntu
  58. HAS_ALL = False
  59. try:
  60. #import curses
  61. #from curses import textpad, panel
  62. HAS_CURSES = True
  63. except ImportError: # Windows
  64. HAS_CURSES = False
  65. try:
  66. import ctypes
  67. HAS_CTYPES = True
  68. # if using `pypy`, pythonapi is not found
  69. IS_PYPY = not hasattr(ctypes, 'pythonapi')
  70. except ImportError: # MacPorts
  71. HAS_CTYPES = False
  72. IS_PYPY = False
  73. IS_PYODIDE = sys.platform == 'emscripten'
  74. # helper objects
  75. class _class:
  76. def _method(self):
  77. pass
  78. # @classmethod
  79. # def _clsmethod(cls): #XXX: test me
  80. # pass
  81. # @staticmethod
  82. # def _static(self): #XXX: test me
  83. # pass
  84. class _class2:
  85. def __call__(self):
  86. pass
  87. _instance2 = _class2()
  88. class _newclass(object):
  89. def _method(self):
  90. pass
  91. # @classmethod
  92. # def _clsmethod(cls): #XXX: test me
  93. # pass
  94. # @staticmethod
  95. # def _static(self): #XXX: test me
  96. # pass
  97. class _newclass2(object):
  98. __slots__ = ['descriptor']
  99. def _function(x): yield x
  100. def _function2():
  101. try: raise
  102. except Exception:
  103. from sys import exc_info
  104. e, er, tb = exc_info()
  105. return er, tb
  106. if HAS_CTYPES:
  107. class _Struct(ctypes.Structure):
  108. pass
  109. _Struct._fields_ = [("_field", ctypes.c_int),("next", ctypes.POINTER(_Struct))]
  110. _filedescrip, _tempfile = tempfile.mkstemp('r') # deleted in cleanup
  111. if sys.hexversion < 0x30d00a1:
  112. _tmpf = tempfile.TemporaryFile('w') # emits OSError 9 in python 3.13
  113. else:
  114. _tmpf = tempfile.NamedTemporaryFile('w').file # for > python 3.9
  115. # objects used by dill for type declaration
  116. registered = d = {}
  117. # objects dill fails to pickle
  118. failures = x = {}
  119. # all other type objects
  120. succeeds = a = {}
  121. # types module (part of CH 8)
  122. a['BooleanType'] = bool(1)
  123. a['BuiltinFunctionType'] = len
  124. a['BuiltinMethodType'] = a['BuiltinFunctionType']
  125. a['BytesType'] = _bytes = codecs.latin_1_encode('\x00')[0] # bytes(1)
  126. a['ClassType'] = _class
  127. a['ComplexType'] = complex(1)
  128. a['DictType'] = _dict = {}
  129. a['DictionaryType'] = a['DictType']
  130. a['FloatType'] = float(1)
  131. a['FunctionType'] = _function
  132. a['InstanceType'] = _instance = _class()
  133. a['IntType'] = _int = int(1)
  134. a['ListType'] = _list = []
  135. a['NoneType'] = None
  136. a['ObjectType'] = object()
  137. a['StringType'] = _str = str(1)
  138. a['TupleType'] = _tuple = ()
  139. a['TypeType'] = type
  140. a['LongType'] = _int
  141. a['UnicodeType'] = _str
  142. # built-in constants (CH 4)
  143. a['CopyrightType'] = copyright
  144. # built-in types (CH 5)
  145. a['ClassObjectType'] = _newclass # <type 'type'>
  146. a['ClassInstanceType'] = _newclass() # <type 'class'>
  147. a['SetType'] = _set = set()
  148. a['FrozenSetType'] = frozenset()
  149. # built-in exceptions (CH 6)
  150. a['ExceptionType'] = _exception = _function2()[0]
  151. # string services (CH 7)
  152. a['SREPatternType'] = _srepattern = re.compile('')
  153. # data types (CH 8)
  154. a['ArrayType'] = array.array("f")
  155. a['DequeType'] = collections.deque([0])
  156. a['DefaultDictType'] = collections.defaultdict(_function, _dict)
  157. a['TZInfoType'] = datetime.tzinfo()
  158. a['DateTimeType'] = datetime.datetime.today()
  159. a['CalendarType'] = calendar.Calendar()
  160. # numeric and mathematical types (CH 9)
  161. a['DecimalType'] = decimal.Decimal(1)
  162. # data compression and archiving (CH 12)
  163. a['TarInfoType'] = tarfile.TarInfo()
  164. # generic operating system services (CH 15)
  165. a['LoggerType'] = _logger = logging.getLogger()
  166. a['FormatterType'] = logging.Formatter() # pickle ok
  167. a['FilterType'] = logging.Filter() # pickle ok
  168. a['LogRecordType'] = logging.makeLogRecord(_dict) # pickle ok
  169. a['OptionParserType'] = _oparser = optparse.OptionParser() # pickle ok
  170. a['OptionGroupType'] = optparse.OptionGroup(_oparser,"foo") # pickle ok
  171. a['OptionType'] = optparse.Option('--foo') # pickle ok
  172. if HAS_CTYPES:
  173. z = x if (IS_PYPY and sys.hexversion < 0x30b0df0) else a
  174. z['CCharType'] = _cchar = ctypes.c_char()
  175. z['CWCharType'] = ctypes.c_wchar() # fail == 2.6
  176. z['CByteType'] = ctypes.c_byte()
  177. z['CUByteType'] = ctypes.c_ubyte()
  178. z['CShortType'] = ctypes.c_short()
  179. z['CUShortType'] = ctypes.c_ushort()
  180. z['CIntType'] = ctypes.c_int()
  181. z['CUIntType'] = ctypes.c_uint()
  182. z['CLongType'] = ctypes.c_long()
  183. z['CULongType'] = ctypes.c_ulong()
  184. z['CLongLongType'] = ctypes.c_longlong()
  185. z['CULongLongType'] = ctypes.c_ulonglong()
  186. z['CFloatType'] = ctypes.c_float()
  187. z['CDoubleType'] = ctypes.c_double()
  188. z['CSizeTType'] = ctypes.c_size_t()
  189. del z
  190. a['CLibraryLoaderType'] = ctypes.cdll
  191. a['StructureType'] = _Struct
  192. # if not IS_PYPY:
  193. # a['BigEndianStructureType'] = ctypes.BigEndianStructure()
  194. #NOTE: also LittleEndianStructureType and UnionType... abstract classes
  195. #NOTE: remember for ctypesobj.contents creates a new python object
  196. #NOTE: ctypes.c_int._objects is memberdescriptor for object's __dict__
  197. #NOTE: base class of all ctypes data types is non-public _CData
  198. import fractions
  199. import io
  200. from io import StringIO as TextIO
  201. # built-in functions (CH 2)
  202. a['ByteArrayType'] = bytearray([1])
  203. # numeric and mathematical types (CH 9)
  204. a['FractionType'] = fractions.Fraction()
  205. a['NumberType'] = numbers.Number()
  206. # generic operating system services (CH 15)
  207. a['IOBaseType'] = io.IOBase()
  208. a['RawIOBaseType'] = io.RawIOBase()
  209. a['TextIOBaseType'] = io.TextIOBase()
  210. a['BufferedIOBaseType'] = io.BufferedIOBase()
  211. a['UnicodeIOType'] = TextIO() # the new StringIO
  212. a['LoggerAdapterType'] = logging.LoggerAdapter(_logger,_dict) # pickle ok
  213. if HAS_CTYPES:
  214. z = x if (IS_PYPY and sys.hexversion < 0x30b0df0) else a
  215. z['CBoolType'] = ctypes.c_bool(1)
  216. z['CLongDoubleType'] = ctypes.c_longdouble()
  217. del z
  218. import argparse
  219. # data types (CH 8)
  220. a['OrderedDictType'] = collections.OrderedDict(_dict)
  221. a['CounterType'] = collections.Counter(_dict)
  222. if HAS_CTYPES:
  223. z = x if (IS_PYPY and sys.hexversion < 0x30b0df0) else a
  224. z['CSSizeTType'] = ctypes.c_ssize_t()
  225. del z
  226. # generic operating system services (CH 15)
  227. a['NullHandlerType'] = logging.NullHandler() # pickle ok # new 2.7
  228. a['ArgParseFileType'] = argparse.FileType() # pickle ok
  229. # -- pickle fails on all below here -----------------------------------------
  230. # types module (part of CH 8)
  231. a['CodeType'] = compile('','','exec')
  232. a['DictProxyType'] = type.__dict__
  233. a['DictProxyType2'] = _newclass.__dict__
  234. a['EllipsisType'] = Ellipsis
  235. a['ClosedFileType'] = open(os.devnull, 'wb', buffering=0).close()
  236. a['GetSetDescriptorType'] = array.array.typecode
  237. a['LambdaType'] = _lambda = lambda x: lambda y: x #XXX: works when not imported!
  238. a['MemberDescriptorType'] = _newclass2.descriptor
  239. if not IS_PYPY:
  240. a['MemberDescriptorType2'] = datetime.timedelta.days
  241. a['MethodType'] = _method = _class()._method #XXX: works when not imported!
  242. a['ModuleType'] = datetime
  243. a['NotImplementedType'] = NotImplemented
  244. a['SliceType'] = slice(1)
  245. a['UnboundMethodType'] = _class._method #XXX: works when not imported!
  246. from dill._dill import get_file_type as openfile
  247. d['TextWrapperType'] = openfile('r', buffering=-1) # same as mode='w','w+','r+'
  248. if not IS_PYODIDE:
  249. d['BufferedRandomType'] = openfile('r+b', buffering=-1) # same as mode='w+b'
  250. d['BufferedReaderType'] = openfile('rb', buffering=-1) # (default: buffering=-1)
  251. d['BufferedWriterType'] = openfile('wb', buffering=-1)
  252. try: # oddities: deprecated
  253. from _pyio import open as _open
  254. d['PyTextWrapperType'] = openfile('r', buffering=-1, open=_open)
  255. if not IS_PYODIDE:
  256. d['PyBufferedRandomType'] = openfile('r+b', buffering=-1, open=_open)
  257. d['PyBufferedReaderType'] = openfile('rb', buffering=-1, open=_open)
  258. d['PyBufferedWriterType'] = openfile('wb', buffering=-1, open=_open)
  259. except ImportError:
  260. pass
  261. del openfile
  262. # other (concrete) object types
  263. z = d if sys.hexversion < 0x30800a2 else a
  264. z['CellType'] = (_lambda)(0).__closure__[0]
  265. del z
  266. a['XRangeType'] = _xrange = range(1)
  267. a['MethodDescriptorType'] = type.__dict__['mro']
  268. a['WrapperDescriptorType'] = type.__repr__
  269. #a['WrapperDescriptorType2'] = type.__dict__['__module__']#XXX: GetSetDescriptor
  270. a['ClassMethodDescriptorType'] = type.__dict__['__prepare__']
  271. # built-in functions (CH 2)
  272. _methodwrap = (1).__lt__
  273. a['MethodWrapperType'] = _methodwrap
  274. a['StaticMethodType'] = staticmethod(_method)
  275. a['ClassMethodType'] = classmethod(_method)
  276. a['PropertyType'] = property()
  277. d['SuperType'] = super(Exception, _exception)
  278. # string services (CH 7)
  279. _in = _bytes
  280. a['InputType'] = _cstrI = StringIO(_in)
  281. a['OutputType'] = _cstrO = StringIO()
  282. # data types (CH 8)
  283. a['WeakKeyDictionaryType'] = weakref.WeakKeyDictionary()
  284. a['WeakValueDictionaryType'] = weakref.WeakValueDictionary()
  285. a['ReferenceType'] = weakref.ref(_instance)
  286. a['DeadReferenceType'] = weakref.ref(_class())
  287. a['ProxyType'] = weakref.proxy(_instance)
  288. a['DeadProxyType'] = weakref.proxy(_class())
  289. a['CallableProxyType'] = weakref.proxy(_instance2)
  290. a['DeadCallableProxyType'] = weakref.proxy(_class2())
  291. a['QueueType'] = Queue.Queue()
  292. # numeric and mathematical types (CH 9)
  293. d['PartialType'] = functools.partial(int,base=2)
  294. a['IzipType'] = zip('0','1')
  295. d['ItemGetterType'] = operator.itemgetter(0)
  296. d['AttrGetterType'] = operator.attrgetter('__repr__')
  297. # file and directory access (CH 10)
  298. _fileW = _cstrO
  299. # data persistence (CH 11)
  300. if HAS_ALL:
  301. x['ConnectionType'] = _conn = sqlite3.connect(':memory:')
  302. x['CursorType'] = _conn.cursor()
  303. a['ShelveType'] = shelve.Shelf({})
  304. # data compression and archiving (CH 12)
  305. if HAS_ALL:
  306. x['BZ2FileType'] = bz2.BZ2File(os.devnull)
  307. x['BZ2CompressorType'] = bz2.BZ2Compressor()
  308. x['BZ2DecompressorType'] = bz2.BZ2Decompressor()
  309. #x['ZipFileType'] = _zip = zipfile.ZipFile(os.devnull,'w')
  310. #_zip.write(_tempfile,'x') [causes annoying warning/error printed on import]
  311. #a['ZipInfoType'] = _zip.getinfo('x')
  312. a['TarFileType'] = tarfile.open(fileobj=_fileW,mode='w')
  313. # file formats (CH 13)
  314. x['DialectType'] = csv.get_dialect('excel')
  315. if sys.hexversion < 0x30d00a1:
  316. import xdrlib
  317. a['PackerType'] = xdrlib.Packer()
  318. # optional operating system services (CH 16)
  319. a['LockType'] = threading.Lock()
  320. a['RLockType'] = threading.RLock()
  321. # generic operating system services (CH 15) # also closed/open and r/w/etc...
  322. a['NamedLoggerType'] = _logger = logging.getLogger(__name__)
  323. #a['FrozenModuleType'] = __hello__ #FIXME: prints "Hello world..."
  324. # interprocess communication (CH 17)
  325. x['SocketType'] = _socket = socket.socket()
  326. x['SocketPairType'] = socket.socketpair()[0]
  327. # python runtime services (CH 27)
  328. a['GeneratorContextManagerType'] = contextlib.contextmanager(max)([1])
  329. #a['ContextType'] = contextvars.Context() #XXX: ContextVar
  330. try: # ipython
  331. __IPYTHON__ is True # is ipython
  332. except NameError:
  333. # built-in constants (CH 4)
  334. a['QuitterType'] = quit
  335. d['ExitType'] = a['QuitterType']
  336. try: # numpy #FIXME: slow... 0.05 to 0.1 sec to import numpy
  337. from numpy import ufunc as _numpy_ufunc
  338. from numpy import array as _numpy_array
  339. from numpy import int32 as _numpy_int32
  340. a['NumpyUfuncType'] = _numpy_ufunc
  341. a['NumpyArrayType'] = _numpy_array
  342. a['NumpyInt32Type'] = _numpy_int32
  343. except ImportError:
  344. pass
  345. # generic operating system services (CH 15)
  346. a['FileHandlerType'] = logging.FileHandler(os.devnull)
  347. a['RotatingFileHandlerType'] = logging.handlers.RotatingFileHandler(os.devnull)
  348. a['SocketHandlerType'] = logging.handlers.SocketHandler('localhost',514)
  349. a['MemoryHandlerType'] = logging.handlers.MemoryHandler(1)
  350. # data types (CH 8)
  351. a['WeakSetType'] = weakref.WeakSet() # 2.7
  352. # generic operating system services (CH 15) [errors when dill is imported]
  353. #a['ArgumentParserType'] = _parser = argparse.ArgumentParser('PROG')
  354. #a['NamespaceType'] = _parser.parse_args() # pickle ok
  355. #a['SubParsersActionType'] = _parser.add_subparsers()
  356. #a['MutuallyExclusiveGroupType'] = _parser.add_mutually_exclusive_group()
  357. #a['ArgumentGroupType'] = _parser.add_argument_group()
  358. # -- dill fails in some versions below here ---------------------------------
  359. # types module (part of CH 8)
  360. d['FileType'] = open(os.devnull, 'rb', buffering=0) # same 'wb','wb+','rb+'
  361. # built-in functions (CH 2)
  362. # Iterators:
  363. a['ListIteratorType'] = iter(_list) # empty vs non-empty
  364. a['SetIteratorType'] = iter(_set) #XXX: empty vs non-empty #FIXME: list_iterator
  365. a['TupleIteratorType']= iter(_tuple) # empty vs non-empty
  366. a['XRangeIteratorType'] = iter(_xrange) # empty vs non-empty
  367. a["BytesIteratorType"] = iter(b'')
  368. a["BytearrayIteratorType"] = iter(bytearray(b''))
  369. z = x if IS_PYPY else a
  370. z["CallableIteratorType"] = iter(iter, None)
  371. del z
  372. x["MemoryIteratorType"] = iter(memoryview(b''))
  373. a["ListReverseiteratorType"] = reversed([])
  374. X = a['OrderedDictType']
  375. d["OdictKeysType"] = X.keys()
  376. d["OdictValuesType"] = X.values()
  377. d["OdictItemsType"] = X.items()
  378. a["OdictIteratorType"] = iter(X.keys()) #FIXME: list_iterator
  379. del X
  380. #FIXME: list_iterator
  381. a['DictionaryItemIteratorType'] = iter(type.__dict__.items())
  382. a['DictionaryKeyIteratorType'] = iter(type.__dict__.keys())
  383. a['DictionaryValueIteratorType'] = iter(type.__dict__.values())
  384. if sys.hexversion >= 0x30800a0:
  385. a["DictReversekeyiteratorType"] = reversed({}.keys())
  386. a["DictReversevalueiteratorType"] = reversed({}.values())
  387. a["DictReverseitemiteratorType"] = reversed({}.items())
  388. try:
  389. import symtable
  390. #FIXME: fails to pickle
  391. x["SymtableEntryType"] = symtable.symtable("", "string", "exec")._table
  392. except ImportError:
  393. pass
  394. if sys.hexversion >= 0x30a00a0 and not IS_PYPY:
  395. x['LineIteratorType'] = compile('3', '', 'eval').co_lines()
  396. if sys.hexversion >= 0x30b00b0 and not IS_PYPY:
  397. from types import GenericAlias
  398. d["GenericAliasIteratorType"] = iter(GenericAlias(list, (int,)))
  399. x['PositionsIteratorType'] = compile('3', '', 'eval').co_positions()
  400. # data types (CH 8)
  401. a['PrettyPrinterType'] = pprint.PrettyPrinter()
  402. # file and directory access (CH 10)
  403. a['TemporaryFileType'] = _tmpf
  404. # data compression and archiving (CH 12)
  405. x['GzipFileType'] = gzip.GzipFile(fileobj=_fileW)
  406. # generic operating system services (CH 15)
  407. a['StreamHandlerType'] = logging.StreamHandler()
  408. # numeric and mathematical types (CH 9)
  409. z = a if sys.hexversion < 0x30e00a1 else x
  410. z['CountType'] = itertools.count(0) #FIXME: __reduce__ removed in 3.14.0a1
  411. z['ChainType'] = itertools.chain('0','1')
  412. z['ProductType'] = itertools.product('0','1')
  413. z['CycleType'] = itertools.cycle('0')
  414. z['PermutationsType'] = itertools.permutations('0')
  415. z['CombinationsType'] = itertools.combinations('0',1)
  416. z['RepeatType'] = itertools.repeat(0)
  417. z['CompressType'] = itertools.compress('0',[1])
  418. del z
  419. #XXX: ...and etc
  420. # -- dill fails on all below here -------------------------------------------
  421. # types module (part of CH 8)
  422. x['GeneratorType'] = _generator = _function(1) #XXX: priority
  423. x['FrameType'] = _generator.gi_frame #XXX: inspect.currentframe()
  424. x['TracebackType'] = _function2()[1] #(see: inspect.getouterframes,getframeinfo)
  425. # other (concrete) object types
  426. # (also: Capsule / CObject ?)
  427. # built-in functions (CH 2)
  428. # built-in types (CH 5)
  429. # string services (CH 7)
  430. x['StructType'] = struct.Struct('c')
  431. x['CallableIteratorType'] = _srepattern.finditer('')
  432. x['SREMatchType'] = _srepattern.match('')
  433. x['SREScannerType'] = _srepattern.scanner('')
  434. x['StreamReader'] = codecs.StreamReader(_cstrI) #XXX: ... and etc
  435. # python object persistence (CH 11)
  436. # x['DbShelveType'] = shelve.open('foo','n')#,protocol=2) #XXX: delete foo
  437. if HAS_ALL:
  438. z = a if IS_PYPY else x
  439. z['DbmType'] = dbm.open(_tempfile,'n')
  440. del z
  441. # x['DbCursorType'] = _dbcursor = anydbm.open('foo','n') #XXX: delete foo
  442. # x['DbType'] = _dbcursor.db
  443. # data compression and archiving (CH 12)
  444. x['ZlibCompressType'] = zlib.compressobj()
  445. x['ZlibDecompressType'] = zlib.decompressobj()
  446. # file formats (CH 13)
  447. x['CSVReaderType'] = csv.reader(_cstrI)
  448. x['CSVWriterType'] = csv.writer(_cstrO)
  449. x['CSVDictReaderType'] = csv.DictReader(_cstrI)
  450. x['CSVDictWriterType'] = csv.DictWriter(_cstrO,{})
  451. # cryptographic services (CH 14)
  452. x['HashType'] = hashlib.md5()
  453. if (sys.hexversion < 0x30800a1):
  454. x['HMACType'] = hmac.new(_in)
  455. else:
  456. x['HMACType'] = hmac.new(_in, digestmod='md5')
  457. # generic operating system services (CH 15)
  458. if HAS_CURSES: pass
  459. #x['CursesWindowType'] = _curwin = curses.initscr() #FIXME: messes up tty
  460. #x['CursesTextPadType'] = textpad.Textbox(_curwin)
  461. #x['CursesPanelType'] = panel.new_panel(_curwin)
  462. if HAS_CTYPES:
  463. x['CCharPType'] = ctypes.c_char_p()
  464. x['CWCharPType'] = ctypes.c_wchar_p()
  465. x['CVoidPType'] = ctypes.c_void_p()
  466. if sys.platform[:3] == 'win':
  467. x['CDLLType'] = _cdll = ctypes.cdll.msvcrt
  468. else:
  469. x['CDLLType'] = _cdll = ctypes.CDLL(None)
  470. if not IS_PYPY:
  471. x['PyDLLType'] = _pydll = ctypes.pythonapi
  472. x['FuncPtrType'] = _cdll._FuncPtr()
  473. x['CCharArrayType'] = ctypes.create_string_buffer(1)
  474. x['CWCharArrayType'] = ctypes.create_unicode_buffer(1)
  475. x['CParamType'] = ctypes.byref(_cchar)
  476. x['LPCCharType'] = ctypes.pointer(_cchar)
  477. x['LPCCharObjType'] = _lpchar = ctypes.POINTER(ctypes.c_char)
  478. x['NullPtrType'] = _lpchar()
  479. x['NullPyObjectType'] = ctypes.py_object()
  480. x['PyObjectType'] = ctypes.py_object(lambda :None)
  481. z = a if IS_PYPY else x
  482. z['FieldType'] = _field = _Struct._field
  483. z['CFUNCTYPEType'] = _cfunc = ctypes.CFUNCTYPE(ctypes.c_char)
  484. if sys.hexversion < 0x30c00b3:
  485. x['CFunctionType'] = _cfunc(str)
  486. del z
  487. # numeric and mathematical types (CH 9)
  488. a['MethodCallerType'] = operator.methodcaller('mro') # 2.6
  489. # built-in types (CH 5)
  490. x['MemoryType'] = memoryview(_in) # 2.7
  491. x['MemoryType2'] = memoryview(bytearray(_in)) # 2.7
  492. d['DictItemsType'] = _dict.items() # 2.7
  493. d['DictKeysType'] = _dict.keys() # 2.7
  494. d['DictValuesType'] = _dict.values() # 2.7
  495. # generic operating system services (CH 15)
  496. a['RawTextHelpFormatterType'] = argparse.RawTextHelpFormatter('PROG')
  497. a['RawDescriptionHelpFormatterType'] = argparse.RawDescriptionHelpFormatter('PROG')
  498. a['ArgDefaultsHelpFormatterType'] = argparse.ArgumentDefaultsHelpFormatter('PROG')
  499. z = a if IS_PYPY else x
  500. z['CmpKeyType'] = _cmpkey = functools.cmp_to_key(_methodwrap) # 2.7, >=3.2
  501. z['CmpKeyObjType'] = _cmpkey('0') #2.7, >=3.2
  502. del z
  503. # oddities: removed, etc
  504. x['BufferType'] = x['MemoryType']
  505. from dill._dill import _testcapsule
  506. if _testcapsule is not None:
  507. d['PyCapsuleType'] = _testcapsule
  508. del _testcapsule
  509. if hasattr(dataclasses, '_HAS_DEFAULT_FACTORY'):
  510. a['DataclassesHasDefaultFactoryType'] = dataclasses._HAS_DEFAULT_FACTORY
  511. if hasattr(dataclasses, 'MISSING'):
  512. a['DataclassesMissingType'] = dataclasses.MISSING
  513. if hasattr(dataclasses, 'KW_ONLY'):
  514. a['DataclassesKWOnlyType'] = dataclasses.KW_ONLY
  515. if hasattr(dataclasses, '_FIELD_BASE'):
  516. a['DataclassesFieldBaseType'] = dataclasses._FIELD
  517. # -- cleanup ----------------------------------------------------------------
  518. a.update(d) # registered also succeed
  519. if sys.platform[:3] == 'win':
  520. os.close(_filedescrip) # required on win32
  521. os.remove(_tempfile)
  522. # EOF