You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
bpo-36540: Documentation for PEP570 - Python positional only arguments (#13202)
* bpo-36540: Documentation for PEP570 - Python positional only arguments
* fixup! bpo-36540: Documentation for PEP570 - Python positional only arguments
* Update reference for compound statements
* Apply suggestions from Carol
Co-Authored-By: Carol Willing <[email protected]>
* Update Doc/tutorial/controlflow.rst
Co-Authored-By: Carol Willing <[email protected]>
* Add extra bullet point and minor edits
TypeError: combined_example() got an unexpected keyword argument 'pos_only'
646
+
647
+
648
+
Finally, consider this function definition which has a potential collision between the positional argument ``name`` and ``**kwds`` which has ``name`` as a key::
649
+
650
+
def foo(name, **kwds):
651
+
return 'name' in kwds
652
+
653
+
There is no possible call that will make it return ``True`` as the keyword ``'name'``
654
+
will always to bind to the first parameter. For example::
655
+
656
+
>>> foo(1, **{'name': 2})
657
+
Traceback (most recent call last):
658
+
File "<stdin>", line 1, in <module>
659
+
TypeError: foo() got multiple values for argument 'name'
660
+
>>>
661
+
662
+
But using ``/`` (positional only arguments), it is possible since it allows ``name`` as a positional argument and ``'name'`` as a key in the keyword arguments::
663
+
664
+
def foo(name, /, **kwds):
665
+
return 'name' in kwds
666
+
>>> foo(1, **{'name': 2})
667
+
True
668
+
669
+
In other words, the names of positional-only parameters can be used in
670
+
``**kwds`` without ambiguity.
671
+
672
+
-----
673
+
Recap
674
+
-----
675
+
676
+
The use case will determine which parameters to use in the function definition::
677
+
678
+
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
679
+
680
+
As guidance:
681
+
682
+
* Use positional-only if you want the name of the parameters to not be
683
+
available to the user. This is useful when parameter names have no real
684
+
meaning, if you want to enforce the order of the arguments when the function
685
+
is called or if you need to take some positional parameters and arbitrary
686
+
keywords.
687
+
* Use keyword-only when names have meaning and the function definition is
688
+
more understandable by being explicit with names or you want to prevent
689
+
users relying on the position of the argument being passed.
690
+
* For an API, use positional-only to prevent prevent breaking API changes
691
+
if the parameter's name is modified in the future.
0 commit comments