Caffe2 - C++ API
A deep learning, cross platform ML framework
structseq.cpp
1 /* Copyright Python Software Foundation
2  *
3  * This file is copy-pasted from CPython source code with modifications:
4  * https://github.com/python/cpython/blob/master/Objects/structseq.c
5  * https://github.com/python/cpython/blob/2.7/Objects/structseq.c
6  *
7  * The purpose of this file is to overwrite the default behavior
8  * of repr of structseq to provide better printting for returned
9  * structseq objects from operators, aka torch.return_types.*
10  *
11  * For more information on copyright of CPython, see:
12  * https://github.com/python/cpython#copyright-and-license-information
13  */
14 
15 #include "torch/csrc/utils/structseq.h"
16 #include "torch/csrc/utils/six.h"
17 #include "structmember.h"
18 #include <sstream>
19 
20 namespace torch {
21 namespace utils {
22 
23 #if PY_MAJOR_VERSION == 2
24 PyObject *structseq_slice(PyStructSequence *obj, Py_ssize_t low, Py_ssize_t high)
25 {
26  PyTupleObject *np;
27  Py_ssize_t i;
28 
29  if (low < 0) {
30  low = 0;
31  }
32  if (high > Py_SIZE(obj)) {
33  high = Py_SIZE(obj);
34  }
35  if (high < low) {
36  high = low;
37  }
38  np = (PyTupleObject *)PyTuple_New(high-low);
39  if (np == nullptr) {
40  return nullptr;
41  }
42  for(i = low; i < high; ++i) {
43  PyObject *v = obj->ob_item[i];
44  Py_INCREF(v);
45  PyTuple_SET_ITEM(np, i-low, v);
46  }
47  return (PyObject *) np;
48 }
49 
50 #define PyUnicode_AsUTF8 PyString_AsString
51 #endif
52 
53 PyObject *returned_structseq_repr(PyStructSequence *obj) {
54  PyTypeObject *typ = Py_TYPE(obj);
55  THPObjectPtr tup = six::maybeAsTuple(obj);
56  if (tup == nullptr) {
57  return nullptr;
58  }
59 
60  std::stringstream ss;
61  ss << typ->tp_name << "(\n";
62  size_t num_elements = Py_SIZE(obj);
63 
64  for (int i=0; i < num_elements; i++) {
65  PyObject *val, *repr;
66  const char *cname, *crepr;
67 
68  cname = typ->tp_members[i].name;
69  if (cname == nullptr) {
70  PyErr_Format(PyExc_SystemError, "In structseq_repr(), member %d name is nullptr"
71  " for type %.500s", i, typ->tp_name);
72  return nullptr;
73  }
74 
75  val = PyTuple_GetItem(tup.get(), i);
76  if (val == nullptr) {
77  return nullptr;
78  }
79 
80  repr = PyObject_Repr(val);
81  if (repr == nullptr) {
82  return nullptr;
83  }
84 
85  crepr = PyUnicode_AsUTF8(repr);
86  Py_DECREF(repr);
87  if (crepr == nullptr) {
88  return nullptr;
89  }
90 
91  ss << cname << '=' << crepr;
92  if (i < num_elements - 1) {
93  ss << ",\n";
94  }
95  }
96  ss << ")";
97 
98  return PyUnicode_FromString(ss.str().c_str());
99 }
100 
101 }
102 }
Definition: jit_type.h:17