File: six.h

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 (52 lines) | stat: -rw-r--r-- 1,465 bytes parent folder | download | duplicates (3)
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
#pragma once

#include <pybind11/pybind11.h>
#include <torch/csrc/utils/object_ptr.h>
#include <torch/csrc/utils/pybind.h>
#include <torch/csrc/utils/structseq.h>

namespace six {

// Usually instances of PyStructSequence is also an instance of tuple
// but in some py2 environment it is not, so we have to manually check
// the name of the type to determine if it is a namedtupled returned
// by a pytorch operator.

inline bool isStructSeq(pybind11::handle input) {
  return pybind11::cast<std::string>(input.get_type().attr("__module__")) ==
      "torch.return_types";
}

inline bool isStructSeq(PyObject* obj) {
  return isStructSeq(pybind11::handle(obj));
}

inline bool isTuple(pybind11::handle input) {
  if (PyTuple_Check(input.ptr())) {
    return true;
  }
  return false;
}

inline bool isTuple(PyObject* obj) {
  return isTuple(pybind11::handle(obj));
}

// maybeAsTuple: if the input is a structseq, then convert it to a tuple
//
// On Python 3, structseq is a subtype of tuple, so these APIs could be used
// directly. But on Python 2, structseq is not a subtype of tuple, so we need to
// manually create a new tuple object from structseq.
inline THPObjectPtr maybeAsTuple(PyStructSequence* obj) {
  Py_INCREF(obj);
  return THPObjectPtr((PyObject*)obj);
}

inline THPObjectPtr maybeAsTuple(PyObject* obj) {
  if (isStructSeq(obj))
    return maybeAsTuple((PyStructSequence*)obj);
  Py_INCREF(obj);
  return THPObjectPtr(obj);
}

} // namespace six