Since python 3.8 introduced positional arguments only, this post need an update.
Positional arguments, keyword arguments, required arguments and optional arguments are often confused. Positional arguments ARE NOT THE SAME AS required arguments. and keywords arguments ARE NOT THE SAME AS optional arguments.
Positional arguments are arguments that can be called by their position in the function definition.
Keyword arguments are arguments that can be called by their name.
Required arguments are arguments that must passed to the function.
Optional arguments are argument that can be not passed to the function. In python optional arguments are arguments that have a default value.
Positional argument that is optional (python 3.8)
def f(a=2, /):
pass
f() # Allowed, argument is optional
f(1) # Allowed, it's a positional argument
f(a=1) # Error, positional only argument
Positional argument that is required (python 3.8)
def f(a, /):
pass
f() # Error, argument required
f(1) # Allowed, it's a positional argument
f(a=1) # Error, positional only argument
Keyword argument that is optional
def f(*, a=1):
pass
f() # Allowed
f(1) # Error, keyword only arguments
f(a=1) # Allowed, it's a keyword argument
keyword argument that is required
def f(*, a)
pass
f() # Error, argument required
f(1) # Error, keyword only arguments
f(a=1) # Allowed, it's a keyword argument
Positional and keyword argument that is optional
def f(a=1)
pass
f() # Allowed, argument is optional
f(1) # Allowed, it's a positional argument
f(a=1) # Allowed, it's a keyword argument
# In fact this function is the same as
def f(*, a=1, /):
pass
Positional and keyword argument that is required
def f(a):
pass
f() # Error, argument required
f(1) # Allowed, it's a positional argument
f(a=1) # Allowed, it's a keyword argument
# In fact this function is the same as
def f(*, a, /):
pass
Conclusion, an argument can be optional or required not both at the same time. It can also be positional, keyword or both at the same time.
Python 3.8 introduced positional only parameters.
def f(positional_argument, /, positional_or_keyword_argument, *, keyword_argument):
pass