Python Glossary Русский

Python 3.8+Functionsconstruct

Positional-only parameters /

parameters

Parameters to the left of / in a def can be passed only by position: f(1, 2), not f(a=1). Many built-ins work this way, len() for example.

Syntax

def f(поз_1, поз_2, /, обычный, *, именованный): ...

The main trap is / and * together: left of / is positional-only, right of * is keyword-only, and in between is either; def f(a, /, *, b) accepts f(1, b=2) and rejects both f(a=1, b=2) and f(1, 2). A positional-only name is not reserved in **kwargs: def f(name, /, **kw) happily accepts f('x', name='y'). Use / when a parameter name carries no meaning or you want to rename it without breaking callers.

Examples

def power(base, exp, /, *, mod=None):
    return pow(base, exp, mod)
print(power(2, 10))  # → 1024
print(power(2, 10, mod=1000))  # → 24
power(2, 10, 1000)  # → TypeError
def power(base, exp, /):
    return base ** exp
power(base=2, exp=10)  # → TypeError
def tag(name, /, **attrs):
    return name, attrs
print(tag('a', name='link'))  # → ('a', {'name': 'link'})
len(obj=[1, 2])  # → TypeError — у len() параметр только позиционный

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy