Something more about positional arguments in python 3.8
Well… You can use the Positional only argument in a way that it can be used as the Keyword argument by using operator ‘/’.
The complete syntax of the positional only argument is:
def name(positional_only_parameters, /, positional_or_keyword_parameters,
*, keyword_only_parameters):
Following the above syntax:
only below are the valid definitions
def name(p1, p2, /, p_or_kw, *, kw):pass
def name(p1, p2=None, /, p_or_kw=None, *, kw):pass
def name(p1, p2=None, /, *, kw):pass
def name(p1, p2=None, /):pass
def name(p1, p2, /, p_or_kw):pass
def name(p1, p2, /):pass
and below are the invalid definitions
def name(p1, p2=None, /, p_or_kw, *, kw):pass
def name(p1=None, p2, /, p_or_kw=None, *, kw):pass
def name(p1=None, p2, /):pass
Example
def foo(a,b,c,d):
print(a,b,c,d)
foo(a=1,b=2,c=3,d=4)#mandatory ,positional arguments used as keyword arguments
foo(1,2,3,4)#used as positional alone
- Output:
1 2 3 4
1 2 3 4
Finished in 0.2s]
By using / in the parameters definition
def foo(a,b,/,c,d):
print(a,b,c,d)
foo(a=1,b=2,c=3,d=4)
The above execution will throw an error
Traceback (most recent call last):
File "C:\deepak\check.py", line 4, in <module>
foo(a=1,b=2,c=3,d=4)
TypeError: foo() got some positional-only arguments passed as keyword arguments: 'a, b'
Where I can call this function only as
foo(1,2,c=3,d=4)
Additional information is most of Cpython built-in features doesn't allow any keyword arguments and in the way we also tend to identify if the feature is the native python feature or cpython’s.
The reason is cpythons feature is used as api by python and the efficient api always allows only positional arguments or try to avoid the keyword arguments in the way to disallow the api user to use the api with wrong keywords and relative exceptional handling costs more. in short ,If a caller of an API starts using a keyword argument, the library author cannot rename the parameter because it would be a breaking change.
For more info please refer
PEP 570 -- Python Positional-Only Parameters
The official home of the Python Programming Language
https://www.python.org/dev/peps/pep-0570/#history-of-positional-only-parameter-semantics-in-python
Regards,
Deepak Rayathurai
Happy Learning