Skip to content

Commit 0dbda6e

Browse files
authored
feat: py::pos_only (#2459)
* feat: py::pos_only * fix: review points from @YannickJadoul * fix: review points from @bstaletic * refactor: kwonly -> kw_only
1 parent 44fa79c commit 0dbda6e

File tree

7 files changed

+182
-58
lines changed

7 files changed

+182
-58
lines changed

docs/advanced/functions.rst

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -378,17 +378,35 @@ argument in a function definition:
378378
f(1, b=2) # good
379379
f(1, 2) # TypeError: f() takes 1 positional argument but 2 were given
380380
381-
Pybind11 provides a ``py::kwonly`` object that allows you to implement
381+
Pybind11 provides a ``py::kw_only`` object that allows you to implement
382382
the same behaviour by specifying the object between positional and keyword-only
383383
argument annotations when registering the function:
384384

385385
.. code-block:: cpp
386386
387387
m.def("f", [](int a, int b) { /* ... */ },
388-
py::arg("a"), py::kwonly(), py::arg("b"));
388+
py::arg("a"), py::kw_only(), py::arg("b"));
389389
390-
Note that, as in Python, you cannot combine this with a ``py::args`` argument.
391-
This feature does *not* require Python 3 to work.
390+
Note that you currently cannot combine this with a ``py::args`` argument. This
391+
feature does *not* require Python 3 to work.
392+
393+
.. versionadded:: 2.6
394+
395+
Positional-only arguments
396+
=========================
397+
398+
Python 3.8 introduced a new positional-only argument syntax, using ``/`` in the
399+
function definition (note that this has been a convention for CPython
400+
positional arguments, such as in ``pow()``, since Python 2). You can
401+
do the same thing in any version of Python using ``py::pos_only()``:
402+
403+
.. code-block:: cpp
404+
405+
m.def("f", [](int a, int b) { /* ... */ },
406+
py::arg("a"), py::pos_only(), py::arg("b"));
407+
408+
You now cannot give argument ``a`` by keyword. This can be combined with
409+
keyword-only arguments, as well.
392410

393411
.. versionadded:: 2.6
394412

docs/changelog.rst

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@ v2.6.0 (IN PROGRESS)
1111

1212
See :ref:`upgrade-guide-2.6` for help upgrading to the new version.
1313

14-
* Keyword only argument supported in Python 2 or 3 with ``py::kwonly()``.
14+
* Keyword-only argument supported in Python 2 or 3 with ``py::kw_only()``.
1515
`#2100 <https://github.com/pybind/pybind11/pull/2100>`_
1616

17+
* Positional-only argument supported in Python 2 or 3 with ``py::pos_only()``.
18+
1719
* Perfect forwarding support for methods.
1820
`#2048 <https://github.com/pybind/pybind11/pull/2048>`_
1921

include/pybind11/attr.h

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ struct function_record {
138138
function_record()
139139
: is_constructor(false), is_new_style_constructor(false), is_stateless(false),
140140
is_operator(false), is_method(false),
141-
has_args(false), has_kwargs(false), has_kwonly_args(false) { }
141+
has_args(false), has_kwargs(false), has_kw_only_args(false) { }
142142

143143
/// Function name
144144
char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
@@ -185,14 +185,17 @@ struct function_record {
185185
/// True if the function has a '**kwargs' argument
186186
bool has_kwargs : 1;
187187

188-
/// True once a 'py::kwonly' is encountered (any following args are keyword-only)
189-
bool has_kwonly_args : 1;
188+
/// True once a 'py::kw_only' is encountered (any following args are keyword-only)
189+
bool has_kw_only_args : 1;
190190

191191
/// Number of arguments (including py::args and/or py::kwargs, if present)
192192
std::uint16_t nargs;
193193

194194
/// Number of trailing arguments (counted in `nargs`) that are keyword-only
195-
std::uint16_t nargs_kwonly = 0;
195+
std::uint16_t nargs_kw_only = 0;
196+
197+
/// Number of leading arguments (counted in `nargs`) that are positional-only
198+
std::uint16_t nargs_pos_only = 0;
196199

197200
/// Python method object
198201
PyMethodDef *def = nullptr;
@@ -366,10 +369,10 @@ template <> struct process_attribute<is_new_style_constructor> : process_attribu
366369
static void init(const is_new_style_constructor &, function_record *r) { r->is_new_style_constructor = true; }
367370
};
368371

369-
inline void process_kwonly_arg(const arg &a, function_record *r) {
372+
inline void process_kw_only_arg(const arg &a, function_record *r) {
370373
if (!a.name || strlen(a.name) == 0)
371-
pybind11_fail("arg(): cannot specify an unnamed argument after an kwonly() annotation");
372-
++r->nargs_kwonly;
374+
pybind11_fail("arg(): cannot specify an unnamed argument after an kw_only() annotation");
375+
++r->nargs_kw_only;
373376
}
374377

375378
/// Process a keyword argument attribute (*without* a default value)
@@ -379,7 +382,7 @@ template <> struct process_attribute<arg> : process_attribute_default<arg> {
379382
r->args.emplace_back("self", nullptr, handle(), true /*convert*/, false /*none not allowed*/);
380383
r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
381384

382-
if (r->has_kwonly_args) process_kwonly_arg(a, r);
385+
if (r->has_kw_only_args) process_kw_only_arg(a, r);
383386
}
384387
};
385388

@@ -412,14 +415,21 @@ template <> struct process_attribute<arg_v> : process_attribute_default<arg_v> {
412415
}
413416
r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
414417

415-
if (r->has_kwonly_args) process_kwonly_arg(a, r);
418+
if (r->has_kw_only_args) process_kw_only_arg(a, r);
416419
}
417420
};
418421

419422
/// Process a keyword-only-arguments-follow pseudo argument
420-
template <> struct process_attribute<kwonly> : process_attribute_default<kwonly> {
421-
static void init(const kwonly &, function_record *r) {
422-
r->has_kwonly_args = true;
423+
template <> struct process_attribute<kw_only> : process_attribute_default<kw_only> {
424+
static void init(const kw_only &, function_record *r) {
425+
r->has_kw_only_args = true;
426+
}
427+
};
428+
429+
/// Process a positional-only-argument maker
430+
template <> struct process_attribute<pos_only> : process_attribute_default<pos_only> {
431+
static void init(const pos_only &, function_record *r) {
432+
r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
423433
}
424434
};
425435

include/pybind11/cast.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1910,7 +1910,12 @@ struct arg_v : arg {
19101910
/// \ingroup annotations
19111911
/// Annotation indicating that all following arguments are keyword-only; the is the equivalent of an
19121912
/// unnamed '*' argument (in Python 3)
1913-
struct kwonly {};
1913+
struct kw_only {};
1914+
1915+
/// \ingroup annotations
1916+
/// Annotation indicating that all previous arguments are positional-only; the is the equivalent of an
1917+
/// unnamed '/' argument (in Python 3.8)
1918+
struct pos_only {};
19141919

19151920
template <typename T>
19161921
arg_v arg::operator=(T &&value) const { return {std::move(*this), std::forward<T>(value)}; }

include/pybind11/pybind11.h

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,13 @@ class cpp_function : public function {
187187
process_attributes<Extra...>::init(extra..., rec);
188188

189189
{
190-
constexpr bool has_kwonly_args = any_of<std::is_same<kwonly, Extra>...>::value,
190+
constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
191+
has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
191192
has_args = any_of<std::is_same<args, Args>...>::value,
192193
has_arg_annotations = any_of<is_keyword<Extra>...>::value;
193-
static_assert(has_arg_annotations || !has_kwonly_args, "py::kwonly requires the use of argument annotations");
194-
static_assert(!(has_args && has_kwonly_args), "py::kwonly cannot be combined with a py::args argument");
194+
static_assert(has_arg_annotations || !has_kw_only_args, "py::kw_only requires the use of argument annotations");
195+
static_assert(has_arg_annotations || !has_pos_only_args, "py::pos_only requires the use of argument annotations (for docstrings and aligning the annotations to the argument)");
196+
static_assert(!(has_args && has_kw_only_args), "py::kw_only cannot be combined with a py::args argument");
195197
}
196198

197199
/* Generate a readable signature describing the function's arguments and return value types */
@@ -257,7 +259,10 @@ class cpp_function : public function {
257259
// Write arg name for everything except *args and **kwargs.
258260
if (*(pc + 1) == '*')
259261
continue;
260-
262+
// Separator for keyword-only arguments, placed before the kw
263+
// arguments start
264+
if (rec->nargs_kw_only > 0 && arg_index + rec->nargs_kw_only == args)
265+
signature += "*, ";
261266
if (arg_index < rec->args.size() && rec->args[arg_index].name) {
262267
signature += rec->args[arg_index].name;
263268
} else if (arg_index == 0 && rec->is_method) {
@@ -272,6 +277,10 @@ class cpp_function : public function {
272277
signature += " = ";
273278
signature += rec->args[arg_index].descr;
274279
}
280+
// Separator for positional-only arguments (placed after the
281+
// argument, rather than before like *
282+
if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only)
283+
signature += ", /";
275284
arg_index++;
276285
} else if (c == '%') {
277286
const std::type_info *t = types[type_index++];
@@ -297,6 +306,7 @@ class cpp_function : public function {
297306
signature += c;
298307
}
299308
}
309+
300310
if (arg_index != args || types[type_index] != nullptr)
301311
pybind11_fail("Internal error while parsing type signature (2)");
302312

@@ -512,7 +522,7 @@ class cpp_function : public function {
512522
size_t num_args = func.nargs; // Number of positional arguments that we need
513523
if (func.has_args) --num_args; // (but don't count py::args
514524
if (func.has_kwargs) --num_args; // or py::kwargs)
515-
size_t pos_args = num_args - func.nargs_kwonly;
525+
size_t pos_args = num_args - func.nargs_kw_only;
516526

517527
if (!func.has_args && n_args_in > pos_args)
518528
continue; // Too many positional arguments for this overload
@@ -561,6 +571,26 @@ class cpp_function : public function {
561571
// We'll need to copy this if we steal some kwargs for defaults
562572
dict kwargs = reinterpret_borrow<dict>(kwargs_in);
563573

574+
// 1.5. Fill in any missing pos_only args from defaults if they exist
575+
if (args_copied < func.nargs_pos_only) {
576+
for (; args_copied < func.nargs_pos_only; ++args_copied) {
577+
const auto &arg = func.args[args_copied];
578+
handle value;
579+
580+
if (arg.value) {
581+
value = arg.value;
582+
}
583+
if (value) {
584+
call.args.push_back(value);
585+
call.args_convert.push_back(arg.convert);
586+
} else
587+
break;
588+
}
589+
590+
if (args_copied < func.nargs_pos_only)
591+
continue; // Not enough defaults to fill the positional arguments
592+
}
593+
564594
// 2. Check kwargs and, failing that, defaults that may help complete the list
565595
if (args_copied < num_args) {
566596
bool copied_kwargs = false;

tests/test_kwargs_and_defaults.cpp

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -95,28 +95,39 @@ TEST_SUBMODULE(kwargs_and_defaults, m) {
9595
// m.def("bad_args7", [](py::kwargs, py::kwargs) {});
9696

9797
// test_keyword_only_args
98-
m.def("kwonly_all", [](int i, int j) { return py::make_tuple(i, j); },
99-
py::kwonly(), py::arg("i"), py::arg("j"));
100-
m.def("kwonly_some", [](int i, int j, int k) { return py::make_tuple(i, j, k); },
101-
py::arg(), py::kwonly(), py::arg("j"), py::arg("k"));
102-
m.def("kwonly_with_defaults", [](int i, int j, int k, int z) { return py::make_tuple(i, j, k, z); },
103-
py::arg() = 3, "j"_a = 4, py::kwonly(), "k"_a = 5, "z"_a);
104-
m.def("kwonly_mixed", [](int i, int j) { return py::make_tuple(i, j); },
105-
"i"_a, py::kwonly(), "j"_a);
106-
m.def("kwonly_plus_more", [](int i, int j, int k, py::kwargs kwargs) {
98+
m.def("kw_only_all", [](int i, int j) { return py::make_tuple(i, j); },
99+
py::kw_only(), py::arg("i"), py::arg("j"));
100+
m.def("kw_only_some", [](int i, int j, int k) { return py::make_tuple(i, j, k); },
101+
py::arg(), py::kw_only(), py::arg("j"), py::arg("k"));
102+
m.def("kw_only_with_defaults", [](int i, int j, int k, int z) { return py::make_tuple(i, j, k, z); },
103+
py::arg() = 3, "j"_a = 4, py::kw_only(), "k"_a = 5, "z"_a);
104+
m.def("kw_only_mixed", [](int i, int j) { return py::make_tuple(i, j); },
105+
"i"_a, py::kw_only(), "j"_a);
106+
m.def("kw_only_plus_more", [](int i, int j, int k, py::kwargs kwargs) {
107107
return py::make_tuple(i, j, k, kwargs); },
108-
py::arg() /* positional */, py::arg("j") = -1 /* both */, py::kwonly(), py::arg("k") /* kw-only */);
108+
py::arg() /* positional */, py::arg("j") = -1 /* both */, py::kw_only(), py::arg("k") /* kw-only */);
109109

110-
m.def("register_invalid_kwonly", [](py::module m) {
111-
m.def("bad_kwonly", [](int i, int j) { return py::make_tuple(i, j); },
112-
py::kwonly(), py::arg() /* invalid unnamed argument */, "j"_a);
110+
m.def("register_invalid_kw_only", [](py::module m) {
111+
m.def("bad_kw_only", [](int i, int j) { return py::make_tuple(i, j); },
112+
py::kw_only(), py::arg() /* invalid unnamed argument */, "j"_a);
113113
});
114114

115+
// test_positional_only_args
116+
m.def("pos_only_all", [](int i, int j) { return py::make_tuple(i, j); },
117+
py::arg("i"), py::arg("j"), py::pos_only());
118+
m.def("pos_only_mix", [](int i, int j) { return py::make_tuple(i, j); },
119+
py::arg("i"), py::pos_only(), py::arg("j"));
120+
m.def("pos_kw_only_mix", [](int i, int j, int k) { return py::make_tuple(i, j, k); },
121+
py::arg("i"), py::pos_only(), py::arg("j"), py::kw_only(), py::arg("k"));
122+
m.def("pos_only_def_mix", [](int i, int j, int k) { return py::make_tuple(i, j, k); },
123+
py::arg("i"), py::arg("j") = 2, py::pos_only(), py::arg("k") = 3);
124+
125+
115126
// These should fail to compile:
116-
// argument annotations are required when using kwonly
117-
// m.def("bad_kwonly1", [](int) {}, py::kwonly());
118-
// can't specify both `py::kwonly` and a `py::args` argument
119-
// m.def("bad_kwonly2", [](int i, py::args) {}, py::kwonly(), "i"_a);
127+
// argument annotations are required when using kw_only
128+
// m.def("bad_kw_only1", [](int) {}, py::kw_only());
129+
// can't specify both `py::kw_only` and a `py::args` argument
130+
// m.def("bad_kw_only2", [](int i, py::args) {}, py::kw_only(), "i"_a);
120131

121132
// test_function_signatures (along with most of the above)
122133
struct KWClass { void foo(int, float) {} };

tests/test_kwargs_and_defaults.py

Lines changed: 66 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -112,43 +112,91 @@ def test_mixed_args_and_kwargs(msg):
112112

113113

114114
def test_keyword_only_args(msg):
115-
assert m.kwonly_all(i=1, j=2) == (1, 2)
116-
assert m.kwonly_all(j=1, i=2) == (2, 1)
115+
assert m.kw_only_all(i=1, j=2) == (1, 2)
116+
assert m.kw_only_all(j=1, i=2) == (2, 1)
117117

118118
with pytest.raises(TypeError) as excinfo:
119-
assert m.kwonly_all(i=1) == (1,)
119+
assert m.kw_only_all(i=1) == (1,)
120120
assert "incompatible function arguments" in str(excinfo.value)
121121

122122
with pytest.raises(TypeError) as excinfo:
123-
assert m.kwonly_all(1, 2) == (1, 2)
123+
assert m.kw_only_all(1, 2) == (1, 2)
124124
assert "incompatible function arguments" in str(excinfo.value)
125125

126-
assert m.kwonly_some(1, k=3, j=2) == (1, 2, 3)
126+
assert m.kw_only_some(1, k=3, j=2) == (1, 2, 3)
127127

128-
assert m.kwonly_with_defaults(z=8) == (3, 4, 5, 8)
129-
assert m.kwonly_with_defaults(2, z=8) == (2, 4, 5, 8)
130-
assert m.kwonly_with_defaults(2, j=7, k=8, z=9) == (2, 7, 8, 9)
131-
assert m.kwonly_with_defaults(2, 7, z=9, k=8) == (2, 7, 8, 9)
128+
assert m.kw_only_with_defaults(z=8) == (3, 4, 5, 8)
129+
assert m.kw_only_with_defaults(2, z=8) == (2, 4, 5, 8)
130+
assert m.kw_only_with_defaults(2, j=7, k=8, z=9) == (2, 7, 8, 9)
131+
assert m.kw_only_with_defaults(2, 7, z=9, k=8) == (2, 7, 8, 9)
132132

133-
assert m.kwonly_mixed(1, j=2) == (1, 2)
134-
assert m.kwonly_mixed(j=2, i=3) == (3, 2)
135-
assert m.kwonly_mixed(i=2, j=3) == (2, 3)
133+
assert m.kw_only_mixed(1, j=2) == (1, 2)
134+
assert m.kw_only_mixed(j=2, i=3) == (3, 2)
135+
assert m.kw_only_mixed(i=2, j=3) == (2, 3)
136136

137-
assert m.kwonly_plus_more(4, 5, k=6, extra=7) == (4, 5, 6, {'extra': 7})
138-
assert m.kwonly_plus_more(3, k=5, j=4, extra=6) == (3, 4, 5, {'extra': 6})
139-
assert m.kwonly_plus_more(2, k=3, extra=4) == (2, -1, 3, {'extra': 4})
137+
assert m.kw_only_plus_more(4, 5, k=6, extra=7) == (4, 5, 6, {'extra': 7})
138+
assert m.kw_only_plus_more(3, k=5, j=4, extra=6) == (3, 4, 5, {'extra': 6})
139+
assert m.kw_only_plus_more(2, k=3, extra=4) == (2, -1, 3, {'extra': 4})
140140

141141
with pytest.raises(TypeError) as excinfo:
142-
assert m.kwonly_mixed(i=1) == (1,)
142+
assert m.kw_only_mixed(i=1) == (1,)
143143
assert "incompatible function arguments" in str(excinfo.value)
144144

145145
with pytest.raises(RuntimeError) as excinfo:
146-
m.register_invalid_kwonly(m)
146+
m.register_invalid_kw_only(m)
147147
assert msg(excinfo.value) == """
148-
arg(): cannot specify an unnamed argument after an kwonly() annotation
148+
arg(): cannot specify an unnamed argument after an kw_only() annotation
149149
"""
150150

151151

152+
def test_positional_only_args(msg):
153+
assert m.pos_only_all(1, 2) == (1, 2)
154+
assert m.pos_only_all(2, 1) == (2, 1)
155+
156+
with pytest.raises(TypeError) as excinfo:
157+
m.pos_only_all(i=1, j=2)
158+
assert "incompatible function arguments" in str(excinfo.value)
159+
160+
assert m.pos_only_mix(1, 2) == (1, 2)
161+
assert m.pos_only_mix(2, j=1) == (2, 1)
162+
163+
with pytest.raises(TypeError) as excinfo:
164+
m.pos_only_mix(i=1, j=2)
165+
assert "incompatible function arguments" in str(excinfo.value)
166+
167+
assert m.pos_kw_only_mix(1, 2, k=3) == (1, 2, 3)
168+
assert m.pos_kw_only_mix(1, j=2, k=3) == (1, 2, 3)
169+
170+
with pytest.raises(TypeError) as excinfo:
171+
m.pos_kw_only_mix(i=1, j=2, k=3)
172+
assert "incompatible function arguments" in str(excinfo.value)
173+
174+
with pytest.raises(TypeError) as excinfo:
175+
m.pos_kw_only_mix(1, 2, 3)
176+
assert "incompatible function arguments" in str(excinfo.value)
177+
178+
with pytest.raises(TypeError) as excinfo:
179+
m.pos_only_def_mix()
180+
assert "incompatible function arguments" in str(excinfo.value)
181+
182+
assert m.pos_only_def_mix(1) == (1, 2, 3)
183+
assert m.pos_only_def_mix(1, 4) == (1, 4, 3)
184+
assert m.pos_only_def_mix(1, 4, 7) == (1, 4, 7)
185+
assert m.pos_only_def_mix(1, 4, k=7) == (1, 4, 7)
186+
187+
with pytest.raises(TypeError) as excinfo:
188+
m.pos_only_def_mix(1, j=4)
189+
assert "incompatible function arguments" in str(excinfo.value)
190+
191+
192+
def test_signatures():
193+
assert "kw_only_all(*, i: int, j: int) -> tuple\n" == m.kw_only_all.__doc__
194+
assert "kw_only_mixed(i: int, *, j: int) -> tuple\n" == m.kw_only_mixed.__doc__
195+
assert "pos_only_all(i: int, j: int, /) -> tuple\n" == m.pos_only_all.__doc__
196+
assert "pos_only_mix(i: int, /, j: int) -> tuple\n" == m.pos_only_mix.__doc__
197+
assert "pos_kw_only_mix(i: int, /, j: int, *, k: int) -> tuple\n" == m.pos_kw_only_mix.__doc__
198+
199+
152200
@pytest.mark.xfail("env.PYPY and env.PY2", reason="PyPy2 doesn't double count")
153201
def test_args_refcount():
154202
"""Issue/PR #1216 - py::args elements get double-inc_ref()ed when combined with regular

0 commit comments

Comments
 (0)