What is the " / " in the built-in list function descriptions - python

At the end of the built-in list function descriptions is "/". What is it?
>>> l=[]
>>> help(l.insert)
Help on built-in function insert:
insert(index, object, /) method of builtins.list instance
Insert object before index.
>>> help(l.index)
Help on built-in function index:
index(value, start=0, stop=9223372036854775807, /) method of builtins.list instance
Return first index of value.

There are three kinds of parameters in Python:
Positional-only, which can only be set by positional arguments
"Regular", which can be set either by positional arguments or keyword arguments
Keyword-only, which can only be set by keyword arguments.
When defining a function, a / is used to separate positional-only parameters (at least one) on the left and the rest on the right. If there is no / in the parameter list, there are no positional-only parameters.
The syntax originated in the argument clinic, which is used to define functions for the CPython implementation. Its use appeared in help for such functions before it was added to the syntax of Python itself in PEP-570.

From Python documentation about help() :
Note that if a slash(/) appears in the parameter list of a function, when invoking help(), it means that the parameters prior to the slash are positional-only.
and from the FAQ entry on positional-only parameters :
What does the slash(/) in the parameter list of a function mean?
A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position. For example, divmod() is a function that accepts positional-only parameters. Its documentation looks like this:
>>> help(divmod)
Help on built-in function divmod in module builtins:
>
> divmod(x, y, /)
> Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
The slash at the end of the parameter list means that both parameters are positional-only. Thus, calling divmod() with keyword arguments would lead to an error:
>>> divmod(x=3, y=4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: divmod() takes no keyword arguments

Related

What is an "/" argument in the docstrings of Python functions? [duplicate]

What does the / mean in Python 3.4's help output for range before the closing parenthesis?
>>> help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return a virtual sequence of numbers from start to stop by step.
|
| Methods defined here:
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
...
It signifies the end of the positional only parameters, parameters you cannot use as keyword parameters. Before Python 3.8, such parameters could only be specified in the C API.
It means the key argument to __contains__ can only be passed in by position (range(5).__contains__(3)), not as a keyword argument (range(5).__contains__(key=3)), something you can do with positional arguments in pure-python functions.
Also see the Argument Clinic documentation:
To mark all parameters as positional-only in Argument Clinic, add a / on a line by itself after the last parameter, indented the same as the parameter lines.
and the (very recent addition to) the Python FAQ:
A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position.
The syntax is now part of the Python language specification, as of version 3.8, see PEP 570 – Python Positional-Only Parameters. Before PEP 570, the syntax was already reserved for possible future inclusion in Python, see PEP 457 - Syntax For Positional-Only Parameters.
Positional-only parameters can lead to cleaner and clearer APIs, make pure-Python implementations of otherwise C-only modules more consistent and easier to maintain, and because positional-only parameters require very little processing, they lead to faster Python code.
I asked this question myself. :) Found out that / was originally proposed by Guido in here.
Alternative proposal: how about using '/' ? It's kind of the opposite
of '*' which means "keyword argument", and '/' is not a new character.
Then his proposal won.
Heh. If that's true, my '/' proposal wins:
def foo(pos_only, /, pos_or_kw, *, kw_only): ...
I think the very relevant document covering this is PEP 570.
Where recap section looks nice.
Recap
The use case will determine which parameters to use in the function definition:
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
As guidance:
Use positional-only if names do not matter or have no meaning, and there are only a few arguments which will always be passed in the same order.
Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names.
If the function ends with /
def foo(p1, p2, /)
This means all functional arguments are positional.
Forward Slash (/) indicates all arguments prior to it are positional only argument. Positional only arguments feature was added in python 3.8 after PEP 570 was accepted. Initially this notation was defined in PEP 457 - Notation for Notation For Positional-Only Parameters
Parameters in function definition prior Foraward slash (/) are positional only and parameters followed by slash(/) can be of any kind as per syntax. Where arguments are mapped to positional only parameters solely based on their position upon calling a function. Passing positional-only parameters by keywords(name) is invalid.
Let's take following example
def foo(a, b, / , x, y):
print("positional ", a, b)
print("positional or keyword", x, y)
Here in the above function definition parameters a and b are positional-only, while x or y can be either positional or keyword.
Following function calls are valid
foo(40, 20, 99, 39)
foo(40, 3.14, "hello", y="world")
foo(1.45, 3.14, x="hello", y="world")
But, following function call is not valid which raises an exception TypeError since a, b are not passed as positional arguments instead passed as keyword
foo(a=1.45, b=3.14, x=1, y=4)
TypeError: foo() got some positional-only arguments passed as keyword
arguments: 'a, b'
Many built in function in python accept positional only arguments where passing arguments by keyword doesn't make sense. For example built-in function len accepts only one positional(only) argument, Where calling len as len(obj="hello world") impairs readability, check help(len).
>>> help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
Positional only parameters make underlying c/library functions easy to maintain. It allows parameters names of positional only parameters to be changes in future without risk of breaking client code that uses API
Last but not least, positional only parameters allow us to use their names to be used in variable length keyword arguments. Check following example
>>> def f(a, b, /, **kwargs):
... print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}
Positional-only parameters syntax was officially added to python3.8. Checkout what's new python3.8 - positional only arguments
PEP Related: PEP 570 -- Python Positional-Only Parameters

What does the ' / ' represent in the method descriptions from help(list)? [duplicate]

What does the / mean in Python 3.4's help output for range before the closing parenthesis?
>>> help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return a virtual sequence of numbers from start to stop by step.
|
| Methods defined here:
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
...
It signifies the end of the positional only parameters, parameters you cannot use as keyword parameters. Before Python 3.8, such parameters could only be specified in the C API.
It means the key argument to __contains__ can only be passed in by position (range(5).__contains__(3)), not as a keyword argument (range(5).__contains__(key=3)), something you can do with positional arguments in pure-python functions.
Also see the Argument Clinic documentation:
To mark all parameters as positional-only in Argument Clinic, add a / on a line by itself after the last parameter, indented the same as the parameter lines.
and the (very recent addition to) the Python FAQ:
A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position.
The syntax is now part of the Python language specification, as of version 3.8, see PEP 570 – Python Positional-Only Parameters. Before PEP 570, the syntax was already reserved for possible future inclusion in Python, see PEP 457 - Syntax For Positional-Only Parameters.
Positional-only parameters can lead to cleaner and clearer APIs, make pure-Python implementations of otherwise C-only modules more consistent and easier to maintain, and because positional-only parameters require very little processing, they lead to faster Python code.
I asked this question myself. :) Found out that / was originally proposed by Guido in here.
Alternative proposal: how about using '/' ? It's kind of the opposite
of '*' which means "keyword argument", and '/' is not a new character.
Then his proposal won.
Heh. If that's true, my '/' proposal wins:
def foo(pos_only, /, pos_or_kw, *, kw_only): ...
I think the very relevant document covering this is PEP 570.
Where recap section looks nice.
Recap
The use case will determine which parameters to use in the function definition:
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
As guidance:
Use positional-only if names do not matter or have no meaning, and there are only a few arguments which will always be passed in the same order.
Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names.
If the function ends with /
def foo(p1, p2, /)
This means all functional arguments are positional.
Forward Slash (/) indicates all arguments prior to it are positional only argument. Positional only arguments feature was added in python 3.8 after PEP 570 was accepted. Initially this notation was defined in PEP 457 - Notation for Notation For Positional-Only Parameters
Parameters in function definition prior Foraward slash (/) are positional only and parameters followed by slash(/) can be of any kind as per syntax. Where arguments are mapped to positional only parameters solely based on their position upon calling a function. Passing positional-only parameters by keywords(name) is invalid.
Let's take following example
def foo(a, b, / , x, y):
print("positional ", a, b)
print("positional or keyword", x, y)
Here in the above function definition parameters a and b are positional-only, while x or y can be either positional or keyword.
Following function calls are valid
foo(40, 20, 99, 39)
foo(40, 3.14, "hello", y="world")
foo(1.45, 3.14, x="hello", y="world")
But, following function call is not valid which raises an exception TypeError since a, b are not passed as positional arguments instead passed as keyword
foo(a=1.45, b=3.14, x=1, y=4)
TypeError: foo() got some positional-only arguments passed as keyword
arguments: 'a, b'
Many built in function in python accept positional only arguments where passing arguments by keyword doesn't make sense. For example built-in function len accepts only one positional(only) argument, Where calling len as len(obj="hello world") impairs readability, check help(len).
>>> help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
Positional only parameters make underlying c/library functions easy to maintain. It allows parameters names of positional only parameters to be changes in future without risk of breaking client code that uses API
Last but not least, positional only parameters allow us to use their names to be used in variable length keyword arguments. Check following example
>>> def f(a, b, /, **kwargs):
... print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}
Positional-only parameters syntax was officially added to python3.8. Checkout what's new python3.8 - positional only arguments
PEP Related: PEP 570 -- Python Positional-Only Parameters

Passing an optional variable in a Python function to extract data from an SQL database [duplicate]

Is there a way in Python to pass optional parameters to a function while calling it and in the function definition have some code based on "only if the optional parameter is passed"
The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.
First, you can use special formal parameter syntax *. If the function definition has a formal parameter preceded by a single *, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.
For instance, here's a function opt_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "optional".
>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
... if ('optional' in keyword_parameters):
... print 'optional parameter found, it is ', keyword_parameters['optional']
... else:
... print 'no optional parameter, sorry'
...
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry
Second, you can supply a default parameter value of some value like None which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.
def my_func(mandatory_arg, optional_arg=100):
print(mandatory_arg, optional_arg)
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values
I find this more readable than using **kwargs.
To determine if an argument was passed at all, I use a custom utility object as the default value:
MISSING = object()
def func(arg=MISSING):
if arg is MISSING:
...
def op(a=4,b=6):
add = a+b
print add
i)op() [o/p: will be (4+6)=10]
ii)op(99) [o/p: will be (99+6)=105]
iii)op(1,1) [o/p: will be (1+1)=2]
Note:
If none or one parameter is passed the default passed parameter will be considered for the function.
If you want give some default value to a parameter assign value in (). like (x =10). But important is first should compulsory argument then default value.
eg.
(y, x =10)
but
(x=10, y) is wrong
You can specify a default value for the optional argument with something that would never passed to the function and check it with the is operator:
class _NO_DEFAULT:
def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()
def func(optional= _NO_DEFAULT):
if optional is _NO_DEFAULT:
print("the optional argument was not passed")
else:
print("the optional argument was:",optional)
then as long as you do not do func(_NO_DEFAULT) you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:
# these two work the same as using **
func()
func(optional=1)
# the optional argument can be positional or keyword unlike using **
func(1)
#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)

What does / mean when showed as a parameter using the help function? [duplicate]

What does the / mean in Python 3.4's help output for range before the closing parenthesis?
>>> help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return a virtual sequence of numbers from start to stop by step.
|
| Methods defined here:
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
...
It signifies the end of the positional only parameters, parameters you cannot use as keyword parameters. Before Python 3.8, such parameters could only be specified in the C API.
It means the key argument to __contains__ can only be passed in by position (range(5).__contains__(3)), not as a keyword argument (range(5).__contains__(key=3)), something you can do with positional arguments in pure-python functions.
Also see the Argument Clinic documentation:
To mark all parameters as positional-only in Argument Clinic, add a / on a line by itself after the last parameter, indented the same as the parameter lines.
and the (very recent addition to) the Python FAQ:
A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position.
The syntax is now part of the Python language specification, as of version 3.8, see PEP 570 – Python Positional-Only Parameters. Before PEP 570, the syntax was already reserved for possible future inclusion in Python, see PEP 457 - Syntax For Positional-Only Parameters.
Positional-only parameters can lead to cleaner and clearer APIs, make pure-Python implementations of otherwise C-only modules more consistent and easier to maintain, and because positional-only parameters require very little processing, they lead to faster Python code.
I asked this question myself. :) Found out that / was originally proposed by Guido in here.
Alternative proposal: how about using '/' ? It's kind of the opposite
of '*' which means "keyword argument", and '/' is not a new character.
Then his proposal won.
Heh. If that's true, my '/' proposal wins:
def foo(pos_only, /, pos_or_kw, *, kw_only): ...
I think the very relevant document covering this is PEP 570.
Where recap section looks nice.
Recap
The use case will determine which parameters to use in the function definition:
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
As guidance:
Use positional-only if names do not matter or have no meaning, and there are only a few arguments which will always be passed in the same order.
Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names.
If the function ends with /
def foo(p1, p2, /)
This means all functional arguments are positional.
Forward Slash (/) indicates all arguments prior to it are positional only argument. Positional only arguments feature was added in python 3.8 after PEP 570 was accepted. Initially this notation was defined in PEP 457 - Notation for Notation For Positional-Only Parameters
Parameters in function definition prior Foraward slash (/) are positional only and parameters followed by slash(/) can be of any kind as per syntax. Where arguments are mapped to positional only parameters solely based on their position upon calling a function. Passing positional-only parameters by keywords(name) is invalid.
Let's take following example
def foo(a, b, / , x, y):
print("positional ", a, b)
print("positional or keyword", x, y)
Here in the above function definition parameters a and b are positional-only, while x or y can be either positional or keyword.
Following function calls are valid
foo(40, 20, 99, 39)
foo(40, 3.14, "hello", y="world")
foo(1.45, 3.14, x="hello", y="world")
But, following function call is not valid which raises an exception TypeError since a, b are not passed as positional arguments instead passed as keyword
foo(a=1.45, b=3.14, x=1, y=4)
TypeError: foo() got some positional-only arguments passed as keyword
arguments: 'a, b'
Many built in function in python accept positional only arguments where passing arguments by keyword doesn't make sense. For example built-in function len accepts only one positional(only) argument, Where calling len as len(obj="hello world") impairs readability, check help(len).
>>> help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
Positional only parameters make underlying c/library functions easy to maintain. It allows parameters names of positional only parameters to be changes in future without risk of breaking client code that uses API
Last but not least, positional only parameters allow us to use their names to be used in variable length keyword arguments. Check following example
>>> def f(a, b, /, **kwargs):
... print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}
Positional-only parameters syntax was officially added to python3.8. Checkout what's new python3.8 - positional only arguments
PEP Related: PEP 570 -- Python Positional-Only Parameters

python "/" in function parameter list [duplicate]

What does the / mean in Python 3.4's help output for range before the closing parenthesis?
>>> help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return a virtual sequence of numbers from start to stop by step.
|
| Methods defined here:
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
...
It signifies the end of the positional only parameters, parameters you cannot use as keyword parameters. Before Python 3.8, such parameters could only be specified in the C API.
It means the key argument to __contains__ can only be passed in by position (range(5).__contains__(3)), not as a keyword argument (range(5).__contains__(key=3)), something you can do with positional arguments in pure-python functions.
Also see the Argument Clinic documentation:
To mark all parameters as positional-only in Argument Clinic, add a / on a line by itself after the last parameter, indented the same as the parameter lines.
and the (very recent addition to) the Python FAQ:
A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position.
The syntax is now part of the Python language specification, as of version 3.8, see PEP 570 – Python Positional-Only Parameters. Before PEP 570, the syntax was already reserved for possible future inclusion in Python, see PEP 457 - Syntax For Positional-Only Parameters.
Positional-only parameters can lead to cleaner and clearer APIs, make pure-Python implementations of otherwise C-only modules more consistent and easier to maintain, and because positional-only parameters require very little processing, they lead to faster Python code.
I asked this question myself. :) Found out that / was originally proposed by Guido in here.
Alternative proposal: how about using '/' ? It's kind of the opposite
of '*' which means "keyword argument", and '/' is not a new character.
Then his proposal won.
Heh. If that's true, my '/' proposal wins:
def foo(pos_only, /, pos_or_kw, *, kw_only): ...
I think the very relevant document covering this is PEP 570.
Where recap section looks nice.
Recap
The use case will determine which parameters to use in the function definition:
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
As guidance:
Use positional-only if names do not matter or have no meaning, and there are only a few arguments which will always be passed in the same order.
Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names.
If the function ends with /
def foo(p1, p2, /)
This means all functional arguments are positional.
Forward Slash (/) indicates all arguments prior to it are positional only argument. Positional only arguments feature was added in python 3.8 after PEP 570 was accepted. Initially this notation was defined in PEP 457 - Notation for Notation For Positional-Only Parameters
Parameters in function definition prior Foraward slash (/) are positional only and parameters followed by slash(/) can be of any kind as per syntax. Where arguments are mapped to positional only parameters solely based on their position upon calling a function. Passing positional-only parameters by keywords(name) is invalid.
Let's take following example
def foo(a, b, / , x, y):
print("positional ", a, b)
print("positional or keyword", x, y)
Here in the above function definition parameters a and b are positional-only, while x or y can be either positional or keyword.
Following function calls are valid
foo(40, 20, 99, 39)
foo(40, 3.14, "hello", y="world")
foo(1.45, 3.14, x="hello", y="world")
But, following function call is not valid which raises an exception TypeError since a, b are not passed as positional arguments instead passed as keyword
foo(a=1.45, b=3.14, x=1, y=4)
TypeError: foo() got some positional-only arguments passed as keyword
arguments: 'a, b'
Many built in function in python accept positional only arguments where passing arguments by keyword doesn't make sense. For example built-in function len accepts only one positional(only) argument, Where calling len as len(obj="hello world") impairs readability, check help(len).
>>> help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
Positional only parameters make underlying c/library functions easy to maintain. It allows parameters names of positional only parameters to be changes in future without risk of breaking client code that uses API
Last but not least, positional only parameters allow us to use their names to be used in variable length keyword arguments. Check following example
>>> def f(a, b, /, **kwargs):
... print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}
Positional-only parameters syntax was officially added to python3.8. Checkout what's new python3.8 - positional only arguments
PEP Related: PEP 570 -- Python Positional-Only Parameters

Categories