_objects.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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-2024 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. try:
  52. import bz2
  53. import sqlite3
  54. import dbm.ndbm as dbm
  55. HAS_ALL = True
  56. except ImportError: # Ubuntu
  57. HAS_ALL = False
  58. try:
  59. #import curses
  60. #from curses import textpad, panel
  61. HAS_CURSES = True
  62. except ImportError: # Windows
  63. HAS_CURSES = False
  64. try:
  65. import ctypes
  66. HAS_CTYPES = True
  67. # if using `pypy`, pythonapi is not found
  68. IS_PYPY = not hasattr(ctypes, 'pythonapi')
  69. except ImportError: # MacPorts
  70. HAS_CTYPES = False
  71. IS_PYPY = False
  72. IS_PYODIDE = sys.platform == 'emscripten'
  73. # helper objects
  74. class _class:
  75. def _method(self):
  76. pass
  77. # @classmethod
  78. # def _clsmethod(cls): #XXX: test me
  79. # pass
  80. # @staticmethod
  81. # def _static(self): #XXX: test me
  82. # pass
  83. class _class2:
  84. def __call__(self):
  85. pass
  86. _instance2 = _class2()
  87. class _newclass(object):
  88. def _method(self):
  89. pass
  90. # @classmethod
  91. # def _clsmethod(cls): #XXX: test me
  92. # pass
  93. # @staticmethod
  94. # def _static(self): #XXX: test me
  95. # pass
  96. class _newclass2(object):
  97. __slots__ = ['descriptor']
  98. def _function(x): yield x
  99. def _function2():
  100. try: raise
  101. except Exception:
  102. from sys import exc_info
  103. e, er, tb = exc_info()
  104. return er, tb
  105. if HAS_CTYPES:
  106. class _Struct(ctypes.Structure):
  107. pass
  108. _Struct._fields_ = [("_field", ctypes.c_int),("next", ctypes.POINTER(_Struct))]
  109. _filedescrip, _tempfile = tempfile.mkstemp('r') # deleted in cleanup
  110. if sys.hexversion < 0x30d00a1:
  111. _tmpf = tempfile.TemporaryFile('w') # emits OSError 9 in python 3.13
  112. else:
  113. _tmpf = tempfile.NamedTemporaryFile('w').file # for > python 3.9
  114. # objects used by dill for type declaration
  115. registered = d = {}
  116. # objects dill fails to pickle
  117. failures = x = {}
  118. # all other type objects
  119. succeeds = a = {}
  120. # types module (part of CH 8)
  121. a['BooleanType'] = bool(1)
  122. a['BuiltinFunctionType'] = len
  123. a['BuiltinMethodType'] = a['BuiltinFunctionType']
  124. a['BytesType'] = _bytes = codecs.latin_1_encode('\x00')[0] # bytes(1)
  125. a['ClassType'] = _class
  126. a['ComplexType'] = complex(1)
  127. a['DictType'] = _dict = {}
  128. a['DictionaryType'] = a['DictType']
  129. a['FloatType'] = float(1)
  130. a['FunctionType'] = _function
  131. a['InstanceType'] = _instance = _class()
  132. a['IntType'] = _int = int(1)
  133. a['ListType'] = _list = []
  134. a['NoneType'] = None
  135. a['ObjectType'] = object()
  136. a['StringType'] = _str = str(1)
  137. a['TupleType'] = _tuple = ()
  138. a['TypeType'] = type
  139. a['LongType'] = _int
  140. a['UnicodeType'] = _str
  141. # built-in constants (CH 4)
  142. a['CopyrightType'] = copyright
  143. # built-in types (CH 5)
  144. a['ClassObjectType'] = _newclass # <type 'type'>
  145. a['ClassInstanceType'] = _newclass() # <type 'class'>
  146. a['SetType'] = _set = set()
  147. a['FrozenSetType'] = frozenset()
  148. # built-in exceptions (CH 6)
  149. a['ExceptionType'] = _exception = _function2()[0]
  150. # string services (CH 7)
  151. a['SREPatternType'] = _srepattern = re.compile('')
  152. # data types (CH 8)
  153. a['ArrayType'] = array.array("f")
  154. a['DequeType'] = collections.deque([0])
  155. a['DefaultDictType'] = collections.defaultdict(_function, _dict)
  156. a['TZInfoType'] = datetime.tzinfo()
  157. a['DateTimeType'] = datetime.datetime.today()
  158. a['CalendarType'] = calendar.Calendar()
  159. # numeric and mathematical types (CH 9)
  160. a['DecimalType'] = decimal.Decimal(1)
  161. a['CountType'] = itertools.count(0)
  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 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 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 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. d['TextWrapperType'] = open(os.devnull, 'r') # same as mode='w','w+','r+'
  247. if not IS_PYODIDE:
  248. d['BufferedRandomType'] = open(os.devnull, 'r+b') # same as mode='w+b'
  249. d['BufferedReaderType'] = open(os.devnull, 'rb') # (default: buffering=-1)
  250. d['BufferedWriterType'] = open(os.devnull, 'wb')
  251. try: # oddities: deprecated
  252. from _pyio import open as _open
  253. d['PyTextWrapperType'] = _open(os.devnull, 'r', buffering=-1)
  254. if not IS_PYODIDE:
  255. d['PyBufferedRandomType'] = _open(os.devnull, 'r+b', buffering=-1)
  256. d['PyBufferedReaderType'] = _open(os.devnull, 'rb', buffering=-1)
  257. d['PyBufferedWriterType'] = _open(os.devnull, 'wb', buffering=-1)
  258. except ImportError:
  259. pass
  260. # other (concrete) object types
  261. z = d if sys.hexversion < 0x30800a2 else a
  262. z['CellType'] = (_lambda)(0).__closure__[0]
  263. del z
  264. a['XRangeType'] = _xrange = range(1)
  265. a['MethodDescriptorType'] = type.__dict__['mro']
  266. a['WrapperDescriptorType'] = type.__repr__
  267. #a['WrapperDescriptorType2'] = type.__dict__['__module__']#XXX: GetSetDescriptor
  268. a['ClassMethodDescriptorType'] = type.__dict__['__prepare__']
  269. # built-in functions (CH 2)
  270. _methodwrap = (1).__lt__
  271. a['MethodWrapperType'] = _methodwrap
  272. a['StaticMethodType'] = staticmethod(_method)
  273. a['ClassMethodType'] = classmethod(_method)
  274. a['PropertyType'] = property()
  275. d['SuperType'] = super(Exception, _exception)
  276. # string services (CH 7)
  277. _in = _bytes
  278. a['InputType'] = _cstrI = StringIO(_in)
  279. a['OutputType'] = _cstrO = StringIO()
  280. # data types (CH 8)
  281. a['WeakKeyDictionaryType'] = weakref.WeakKeyDictionary()
  282. a['WeakValueDictionaryType'] = weakref.WeakValueDictionary()
  283. a['ReferenceType'] = weakref.ref(_instance)
  284. a['DeadReferenceType'] = weakref.ref(_class())
  285. a['ProxyType'] = weakref.proxy(_instance)
  286. a['DeadProxyType'] = weakref.proxy(_class())
  287. a['CallableProxyType'] = weakref.proxy(_instance2)
  288. a['DeadCallableProxyType'] = weakref.proxy(_class2())
  289. a['QueueType'] = Queue.Queue()
  290. # numeric and mathematical types (CH 9)
  291. d['PartialType'] = functools.partial(int,base=2)
  292. a['IzipType'] = zip('0','1')
  293. a['ChainType'] = itertools.chain('0','1')
  294. d['ItemGetterType'] = operator.itemgetter(0)
  295. d['AttrGetterType'] = operator.attrgetter('__repr__')
  296. # file and directory access (CH 10)
  297. _fileW = _cstrO
  298. # data persistence (CH 11)
  299. if HAS_ALL:
  300. x['ConnectionType'] = _conn = sqlite3.connect(':memory:')
  301. x['CursorType'] = _conn.cursor()
  302. a['ShelveType'] = shelve.Shelf({})
  303. # data compression and archiving (CH 12)
  304. if HAS_ALL:
  305. x['BZ2FileType'] = bz2.BZ2File(os.devnull)
  306. x['BZ2CompressorType'] = bz2.BZ2Compressor()
  307. x['BZ2DecompressorType'] = bz2.BZ2Decompressor()
  308. #x['ZipFileType'] = _zip = zipfile.ZipFile(os.devnull,'w')
  309. #_zip.write(_tempfile,'x') [causes annoying warning/error printed on import]
  310. #a['ZipInfoType'] = _zip.getinfo('x')
  311. a['TarFileType'] = tarfile.open(fileobj=_fileW,mode='w')
  312. # file formats (CH 13)
  313. x['DialectType'] = csv.get_dialect('excel')
  314. if sys.hexversion < 0x30d00a1:
  315. import xdrlib
  316. a['PackerType'] = xdrlib.Packer()
  317. # optional operating system services (CH 16)
  318. a['LockType'] = threading.Lock()
  319. a['RLockType'] = threading.RLock()
  320. # generic operating system services (CH 15) # also closed/open and r/w/etc...
  321. a['NamedLoggerType'] = _logger = logging.getLogger(__name__)
  322. #a['FrozenModuleType'] = __hello__ #FIXME: prints "Hello world..."
  323. # interprocess communication (CH 17)
  324. x['SocketType'] = _socket = socket.socket()
  325. x['SocketPairType'] = socket.socketpair()[0]
  326. # python runtime services (CH 27)
  327. a['GeneratorContextManagerType'] = contextlib.contextmanager(max)([1])
  328. try: # ipython
  329. __IPYTHON__ is True # is ipython
  330. except NameError:
  331. # built-in constants (CH 4)
  332. a['QuitterType'] = quit
  333. d['ExitType'] = a['QuitterType']
  334. try: # numpy #FIXME: slow... 0.05 to 0.1 sec to import numpy
  335. from numpy import ufunc as _numpy_ufunc
  336. from numpy import array as _numpy_array
  337. from numpy import int32 as _numpy_int32
  338. a['NumpyUfuncType'] = _numpy_ufunc
  339. a['NumpyArrayType'] = _numpy_array
  340. a['NumpyInt32Type'] = _numpy_int32
  341. except ImportError:
  342. pass
  343. # numeric and mathematical types (CH 9)
  344. a['ProductType'] = itertools.product('0','1')
  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:
  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. # numeric and mathematical types (CH 9)
  403. a['CycleType'] = itertools.cycle('0')
  404. # file and directory access (CH 10)
  405. a['TemporaryFileType'] = _tmpf
  406. # data compression and archiving (CH 12)
  407. x['GzipFileType'] = gzip.GzipFile(fileobj=_fileW)
  408. # generic operating system services (CH 15)
  409. a['StreamHandlerType'] = logging.StreamHandler()
  410. # numeric and mathematical types (CH 9)
  411. a['PermutationsType'] = itertools.permutations('0')
  412. a['CombinationsType'] = itertools.combinations('0',1)
  413. a['RepeatType'] = itertools.repeat(0)
  414. a['CompressType'] = itertools.compress('0',[1])
  415. #XXX: ...and etc
  416. # -- dill fails on all below here -------------------------------------------
  417. # types module (part of CH 8)
  418. x['GeneratorType'] = _generator = _function(1) #XXX: priority
  419. x['FrameType'] = _generator.gi_frame #XXX: inspect.currentframe()
  420. x['TracebackType'] = _function2()[1] #(see: inspect.getouterframes,getframeinfo)
  421. # other (concrete) object types
  422. # (also: Capsule / CObject ?)
  423. # built-in functions (CH 2)
  424. # built-in types (CH 5)
  425. # string services (CH 7)
  426. x['StructType'] = struct.Struct('c')
  427. x['CallableIteratorType'] = _srepattern.finditer('')
  428. x['SREMatchType'] = _srepattern.match('')
  429. x['SREScannerType'] = _srepattern.scanner('')
  430. x['StreamReader'] = codecs.StreamReader(_cstrI) #XXX: ... and etc
  431. # python object persistence (CH 11)
  432. # x['DbShelveType'] = shelve.open('foo','n')#,protocol=2) #XXX: delete foo
  433. if HAS_ALL:
  434. z = a if IS_PYPY else x
  435. z['DbmType'] = dbm.open(_tempfile,'n')
  436. del z
  437. # x['DbCursorType'] = _dbcursor = anydbm.open('foo','n') #XXX: delete foo
  438. # x['DbType'] = _dbcursor.db
  439. # data compression and archiving (CH 12)
  440. x['ZlibCompressType'] = zlib.compressobj()
  441. x['ZlibDecompressType'] = zlib.decompressobj()
  442. # file formats (CH 13)
  443. x['CSVReaderType'] = csv.reader(_cstrI)
  444. x['CSVWriterType'] = csv.writer(_cstrO)
  445. x['CSVDictReaderType'] = csv.DictReader(_cstrI)
  446. x['CSVDictWriterType'] = csv.DictWriter(_cstrO,{})
  447. # cryptographic services (CH 14)
  448. x['HashType'] = hashlib.md5()
  449. if (sys.hexversion < 0x30800a1):
  450. x['HMACType'] = hmac.new(_in)
  451. else:
  452. x['HMACType'] = hmac.new(_in, digestmod='md5')
  453. # generic operating system services (CH 15)
  454. if HAS_CURSES: pass
  455. #x['CursesWindowType'] = _curwin = curses.initscr() #FIXME: messes up tty
  456. #x['CursesTextPadType'] = textpad.Textbox(_curwin)
  457. #x['CursesPanelType'] = panel.new_panel(_curwin)
  458. if HAS_CTYPES:
  459. x['CCharPType'] = ctypes.c_char_p()
  460. x['CWCharPType'] = ctypes.c_wchar_p()
  461. x['CVoidPType'] = ctypes.c_void_p()
  462. if sys.platform[:3] == 'win':
  463. x['CDLLType'] = _cdll = ctypes.cdll.msvcrt
  464. else:
  465. x['CDLLType'] = _cdll = ctypes.CDLL(None)
  466. if not IS_PYPY:
  467. x['PyDLLType'] = _pydll = ctypes.pythonapi
  468. x['FuncPtrType'] = _cdll._FuncPtr()
  469. x['CCharArrayType'] = ctypes.create_string_buffer(1)
  470. x['CWCharArrayType'] = ctypes.create_unicode_buffer(1)
  471. x['CParamType'] = ctypes.byref(_cchar)
  472. x['LPCCharType'] = ctypes.pointer(_cchar)
  473. x['LPCCharObjType'] = _lpchar = ctypes.POINTER(ctypes.c_char)
  474. x['NullPtrType'] = _lpchar()
  475. x['NullPyObjectType'] = ctypes.py_object()
  476. x['PyObjectType'] = ctypes.py_object(lambda :None)
  477. z = a if IS_PYPY else x
  478. z['FieldType'] = _field = _Struct._field
  479. z['CFUNCTYPEType'] = _cfunc = ctypes.CFUNCTYPE(ctypes.c_char)
  480. if sys.hexversion < 0x30c00b3:
  481. x['CFunctionType'] = _cfunc(str)
  482. del z
  483. # numeric and mathematical types (CH 9)
  484. a['MethodCallerType'] = operator.methodcaller('mro') # 2.6
  485. # built-in types (CH 5)
  486. x['MemoryType'] = memoryview(_in) # 2.7
  487. x['MemoryType2'] = memoryview(bytearray(_in)) # 2.7
  488. d['DictItemsType'] = _dict.items() # 2.7
  489. d['DictKeysType'] = _dict.keys() # 2.7
  490. d['DictValuesType'] = _dict.values() # 2.7
  491. # generic operating system services (CH 15)
  492. a['RawTextHelpFormatterType'] = argparse.RawTextHelpFormatter('PROG')
  493. a['RawDescriptionHelpFormatterType'] = argparse.RawDescriptionHelpFormatter('PROG')
  494. a['ArgDefaultsHelpFormatterType'] = argparse.ArgumentDefaultsHelpFormatter('PROG')
  495. z = a if IS_PYPY else x
  496. z['CmpKeyType'] = _cmpkey = functools.cmp_to_key(_methodwrap) # 2.7, >=3.2
  497. z['CmpKeyObjType'] = _cmpkey('0') #2.7, >=3.2
  498. del z
  499. # oddities: removed, etc
  500. x['BufferType'] = x['MemoryType']
  501. from dill._dill import _testcapsule
  502. if _testcapsule is not None:
  503. d['PyCapsuleType'] = _testcapsule
  504. del _testcapsule
  505. if hasattr(dataclasses, '_HAS_DEFAULT_FACTORY'):
  506. a['DataclassesHasDefaultFactoryType'] = dataclasses._HAS_DEFAULT_FACTORY
  507. if hasattr(dataclasses, 'MISSING'):
  508. a['DataclassesMissingType'] = dataclasses.MISSING
  509. if hasattr(dataclasses, 'KW_ONLY'):
  510. a['DataclassesKWOnlyType'] = dataclasses.KW_ONLY
  511. if hasattr(dataclasses, '_FIELD_BASE'):
  512. a['DataclassesFieldBaseType'] = dataclasses._FIELD
  513. # -- cleanup ----------------------------------------------------------------
  514. a.update(d) # registered also succeed
  515. if sys.platform[:3] == 'win':
  516. os.close(_filedescrip) # required on win32
  517. os.remove(_tempfile)
  518. # EOF