Debian Codegraph @

src/Base/PyWrapParseTupleAndKeywords.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /****************************************************************************
3 * *
4 * Copyright (c) 2023 The FreeCAD Project Association *
5 * *
6 * This file is part of FreeCAD. *
7 * *
8 * FreeCAD is free software: you can redistribute it and/or modify it *
9 * under the terms of the GNU Lesser General Public License as *
10 * published by the Free Software Foundation, either version 2.1 of the *
11 * License, or (at your option) any later version. *
12 * *
13 * FreeCAD is distributed in the hope that it will be useful, but *
14 * WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
16 * Lesser General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Lesser General Public *
19 * License along with FreeCAD. If not, see *
20 * <https://www.gnu.org/licenses/>. *
21 * *
22 ***************************************************************************/
23
24 #ifndef FREECAD_PYWRAPPARSETUPLEANDKEYWORDS_H
25 #define FREECAD_PYWRAPPARSETUPLEANDKEYWORDS_H
26
27 #include <Python.h>
28 #include <array>
29
30 namespace Base
31 {
32
33 /// A thin C++ wrapper around PyArg_ParseTupleAndKeywords providing const-correctness for the
34 /// keywords argument \arg args The Python args object \arg kw The Python kw object \arg format The
35 /// format string describing the expected arguments \arg keywords A std::array of keywords,
36 /// terminated by a nullptr (required by CPython) \arg (variadic) Pointers to the storage locations
37 /// for the parameters \returns boolean true on success, or false on failure
38 template<size_t arraySize>
39 bool Wrapped_ParseTupleAndKeywords(
40 PyObject* args,
41 PyObject* kw,
42 const char* format,
43 const std::array<const char*, arraySize> keywords,
44 ...
45 )
46 {
47 static_assert(arraySize > 0, "keywords array must have at least a single nullptr in it");
48 if (keywords.back()) {
49 PyErr_SetString(PyExc_ValueError, "Last element of keywords array is not null");
50 return false;
51 }
52
53 // NOTE: This code is from getargs.c in the Python source code (modified to use the public
54 // interface at PyArg_VaParseTupleAndKeywords and to return a bool).
55
56 if ((args == nullptr || !PyTuple_Check(args)) || (kw != nullptr && !PyDict_Check(kw))
57 || format == nullptr) {
58 PyErr_BadInternalCall();
59 return false;
60 }
61
62 va_list va; // NOLINT
63 va_start(va, keywords);
64 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
65 int retval
66 = PyArg_VaParseTupleAndKeywords(args, kw, format, const_cast<char**>(keywords.data()), va);
67 va_end(va);
68 return retval != 0; // Convert to a true C++ boolean
69 }
70
71 } // namespace Base
72
73 #endif // FREECAD_PYWRAPPARSETUPLEANDKEYWORDS_H