test_objects.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. demonstrate dill's ability to pickle different python types
  10. test pickling of all Python Standard Library objects (currently: CH 1-14 @ 2.7)
  11. """
  12. import dill as pickle
  13. pickle.settings['recurse'] = True
  14. #pickle.detect.trace(True)
  15. #import pickle
  16. # get all objects for testing
  17. from dill import load_types, objects, extend
  18. load_types(pickleable=True,unpickleable=False)
  19. # uncomment the next two lines to test cloudpickle
  20. #extend(False)
  21. #import cloudpickle as pickle
  22. # helper objects
  23. class _class:
  24. def _method(self):
  25. pass
  26. # objects that *fail* if imported
  27. special = {}
  28. special['LambdaType'] = _lambda = lambda x: lambda y: x
  29. special['MethodType'] = _method = _class()._method
  30. special['UnboundMethodType'] = _class._method
  31. objects.update(special)
  32. def pickles(name, exact=False, verbose=True):
  33. """quick check if object pickles with dill"""
  34. obj = objects[name]
  35. try:
  36. pik = pickle.loads(pickle.dumps(obj))
  37. if exact:
  38. try:
  39. assert pik == obj
  40. except AssertionError:
  41. assert type(obj) == type(pik)
  42. if verbose: print ("weak: %s %s" % (name, type(obj)))
  43. else:
  44. assert type(obj) == type(pik)
  45. except Exception:
  46. if verbose: print ("fails: %s %s" % (name, type(obj)))
  47. def test_objects(verbose=True):
  48. for member in objects.keys():
  49. #pickles(member, exact=True, verbose=verbose)
  50. pickles(member, exact=False, verbose=verbose)
  51. if __name__ == '__main__':
  52. import warnings
  53. warnings.simplefilter('ignore')
  54. test_objects(verbose=False)