File: structseq.cpp

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (76 lines) | stat: -rw-r--r-- 2,090 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* Copyright Python Software Foundation
 *
 * This file is copy-pasted from CPython source code with modifications:
 * https://github.com/python/cpython/blob/master/Objects/structseq.c
 * https://github.com/python/cpython/blob/2.7/Objects/structseq.c
 *
 * The purpose of this file is to overwrite the default behavior
 * of repr of structseq to provide better printting for returned
 * structseq objects from operators, aka torch.return_types.*
 *
 * For more information on copyright of CPython, see:
 * https://github.com/python/cpython#copyright-and-license-information
 */

#include <torch/csrc/utils/six.h>
#include <torch/csrc/utils/structseq.h>
#include <sstream>

#include <structmember.h>

namespace torch {
namespace utils {

// NOTE: The built-in repr method from PyStructSequence was updated in
// https://github.com/python/cpython/commit/c70ab02df2894c34da2223fc3798c0404b41fd79
// so this function might not be required in Python 3.8+.
PyObject* returned_structseq_repr(PyStructSequence* obj) {
  PyTypeObject* typ = Py_TYPE(obj);
  THPObjectPtr tup = six::maybeAsTuple(obj);
  if (tup == nullptr) {
    return nullptr;
  }

  std::stringstream ss;
  ss << typ->tp_name << "(\n";
  Py_ssize_t num_elements = Py_SIZE(obj);

  for (Py_ssize_t i = 0; i < num_elements; i++) {
    const char* cname = typ->tp_members[i].name;
    if (cname == nullptr) {
      PyErr_Format(
          PyExc_SystemError,
          "In structseq_repr(), member %zd name is nullptr"
          " for type %.500s",
          i,
          typ->tp_name);
      return nullptr;
    }

    PyObject* val = PyTuple_GetItem(tup.get(), i);
    if (val == nullptr) {
      return nullptr;
    }

    auto repr = THPObjectPtr(PyObject_Repr(val));
    if (repr == nullptr) {
      return nullptr;
    }

    const char* crepr = PyUnicode_AsUTF8(repr);
    if (crepr == nullptr) {
      return nullptr;
    }

    ss << cname << '=' << crepr;
    if (i < num_elements - 1) {
      ss << ",\n";
    }
  }
  ss << ")";

  return PyUnicode_FromString(ss.str().c_str());
}

} // namespace utils
} // namespace torch