| 28 | }; |
| 29 | |
| 30 | void init_print(nb::module_& m) { |
| 31 | // Set Python print formatting options |
| 32 | mx::get_global_formatter().capitalize_bool = true; |
| 33 | // Expose printing options to Python: allow setting global precision. |
| 34 | nb::class_<mx::PrintOptions>(m, "PrintOptions") |
| 35 | .def(nb::init<int>(), "precision"_a = -1) |
| 36 | .def_rw("precision", &mx::PrintOptions::precision); |
| 37 | |
| 38 | m.def( |
| 39 | "set_printoptions", |
| 40 | [](int precision) { mx::set_printoptions({precision}); }, |
| 41 | "precision"_a = mx::get_global_formatter().format_options.precision, |
| 42 | R"pbdoc( |
| 43 | Set global printing precision for array formatting. |
| 44 | |
| 45 | Example: |
| 46 | >>> print(x) # Uses default precision |
| 47 | >>> mx.set_printoptions(precision=3): |
| 48 | >>> print(x) # Uses precision of 3 |
| 49 | >>> print(x) # Uses precision of 3 (again) |
| 50 | |
| 51 | Args: |
| 52 | precision (int): Number of decimal places. |
| 53 | )pbdoc"); |
| 54 | m.def( |
| 55 | "get_printoptions", |
| 56 | []() { return mx::get_global_formatter().format_options; }, |
| 57 | R"pbdoc( |
| 58 | Get global printing precision for array formatting. |
| 59 | |
| 60 | Returns: |
| 61 | PrintOptions: The format options used for printing arrays. |
| 62 | )pbdoc"); |
| 63 | |
| 64 | nb::class_<PrintOptionsContext>(m, "_PrintOptionsContext") |
| 65 | .def(nb::init<mx::PrintOptions>()) |
| 66 | .def("__enter__", &PrintOptionsContext::enter) |
| 67 | .def("__exit__", &PrintOptionsContext::exit); |
| 68 | |
| 69 | m.def( |
| 70 | "printoptions", |
| 71 | [](int precision) { return PrintOptionsContext({precision}); }, |
| 72 | "precision"_a = mx::get_global_formatter().format_options.precision, |
| 73 | R"pbdoc( |
| 74 | Context manager for setting print options temporarily. |
| 75 | |
| 76 | Example: |
| 77 | >>> print(x) # Uses default precision |
| 78 | >>> with mx.printoptions(precision=3): |
| 79 | >>> print(x) # Uses precision of 3 |
| 80 | >>> print(x) # Back to default precision |
| 81 | |
| 82 | |
| 83 | Args: |
| 84 | precision (int): Number of decimal places. Use -1 for default |
| 85 | )pbdoc"); |
| 86 | } |
no test coverage detected