• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //  (C) Copyright R.W. Grosse-Kunstleve 2002.
2 //  Distributed under the Boost Software License, Version 1.0. (See
3 //  accompanying file LICENSE_1_0.txt or copy at
4 //  http://www.boost.org/LICENSE_1_0.txt)
5 
6 #include <boost/python/make_function.hpp>
7 #include <boost/python/object/class.hpp>
8 #include <boost/python/tuple.hpp>
9 #include <boost/python/list.hpp>
10 #include <boost/python/dict.hpp>
11 #include <boost/python/str.hpp>
12 
13 namespace boost { namespace python {
14 
15 namespace {
16 
instance_reduce(object instance_obj)17   tuple instance_reduce(object instance_obj)
18   {
19       list result;
20       object instance_class(instance_obj.attr("__class__"));
21       result.append(instance_class);
22       object none;
23       if (!getattr(instance_obj, "__safe_for_unpickling__", none))
24       {
25           str type_name(getattr(instance_class, "__name__"));
26           str module_name(getattr(instance_class, "__module__", object("")));
27           if (module_name)
28               module_name += ".";
29 
30           PyErr_SetObject(
31                PyExc_RuntimeError,
32                ( "Pickling of \"%s\" instances is not enabled"
33                  " (http://www.boost.org/libs/python/doc/v2/pickle.html)"
34                   % (module_name+type_name)).ptr()
35           );
36 
37           throw_error_already_set();
38       }
39       object getinitargs = getattr(instance_obj, "__getinitargs__", none);
40       tuple initargs;
41       if (!getinitargs.is_none()) {
42           initargs = tuple(getinitargs());
43       }
44       result.append(initargs);
45       object getstate = getattr(instance_obj, "__getstate__", none);
46       object instance_dict = getattr(instance_obj, "__dict__", none);
47       long len_instance_dict = 0;
48       if (!instance_dict.is_none()) {
49           len_instance_dict = len(instance_dict);
50       }
51       if (!getstate.is_none()) {
52           if (len_instance_dict > 0) {
53               object getstate_manages_dict = getattr(
54                 instance_obj, "__getstate_manages_dict__", none);
55               if (getstate_manages_dict.is_none()) {
56                   PyErr_SetString(PyExc_RuntimeError,
57                     "Incomplete pickle support"
58                     " (__getstate_manages_dict__ not set)");
59                   throw_error_already_set();
60               }
61           }
62           result.append(getstate());
63       }
64       else if (len_instance_dict > 0) {
65           result.append(instance_dict);
66       }
67       return tuple(result);
68   }
69 
70 } // namespace
71 
make_instance_reduce_function()72 object const& make_instance_reduce_function()
73 {
74     static object result(&instance_reduce);
75     return result;
76 }
77 
78 }} // namespace boost::python
79