1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/compiler/xla/python/py_traceback.h"
17
18 #include "absl/strings/str_format.h"
19 #include "pybind11/pybind11.h"
20 #include "pybind11/stl.h"
21 #include "tensorflow/compiler/xla/python/traceback.h"
22
23 namespace xla {
24
25 namespace py = pybind11;
26
BuildTracebackSubmodule(py::module & m)27 void BuildTracebackSubmodule(py::module& m) {
28 py::class_<Traceback::Frame>(m, "Frame")
29 .def_readonly("file_name", &Traceback::Frame::file_name)
30 .def_readonly("function_name", &Traceback::Frame::function_name)
31 .def_readonly("function_start_line",
32 &Traceback::Frame::function_start_line)
33 .def_readonly("line_num", &Traceback::Frame::line_num)
34 .def("__repr__", [](const Traceback::Frame& frame) {
35 return absl::StrFormat("%s;%s:%d", frame.function_name, frame.file_name,
36 frame.line_num);
37 });
38
39 py::class_<Traceback, std::shared_ptr<Traceback>> traceback(
40 m, "Traceback", "Represents a Python stack trace.");
41 traceback.def_property_static(
42 "enabled", [](py::object /* cls */) { return Traceback::enabled(); },
43 [](py::object /* cls */, bool enabled) {
44 return Traceback::SetEnabled(enabled);
45 });
46 traceback.def_static(
47 "get_traceback", []() { return Traceback::Get(); },
48 R"doc(
49 Returns a :class:`Traceback` for the current thread.
50
51 If ``Traceback.enabled`` is ``True``, returns a :class:`Traceback` object
52 that describes the Python stack of the calling thread. Stack trace
53 collection has a small overhead, so it is disabled by default. If traceback
54 collection is disabled, returns ``None``.
55 )doc");
56 traceback.def_property_readonly("frames", &Traceback::Frames);
57 traceback.def("__str__", &Traceback::ToString);
58 }
59
60 } // namespace xla
61