Salim Boukerma
Salim Boukerma

Reputation: 11

About positional and keyword arguments

def test_args_2(x, y, z): print(x, y, z)

When calling that function with :

test_args_2(4, y=4)

Python gives:

TypeError: test_args_2() missing 1 required positional argument: 'z'

z is missing but it's considered positional not a keyword one, why ?

if we modify the call by this:

test_args_2(4, y=5, 4)

Python gives:

SyntaxError: positional argument follows keyword argument

Why z is considered positional although in the second error message it's assumed keyword one?

Upvotes: 1

Views: 1389

Answers (2)

zeeshan12396
zeeshan12396

Reputation: 412

def test_args_2(x, y, z):
    print(x, y, z)
test_args_2(4, y=4)  #not allow
test_args_2(x=4,y=2,z=5) #allow
test_args_2(y=2,z=5,x=4) #allow 

Positional arguments are arguments that can be called by their position in the function call.
x,y,z are the positional arguments , all three are required

def test_args_2(x, y, z=0):
    print(x, y, z)
test_args_2(1,2) # allow  

The error positional argument follows keyword argument means that the if any keyword argument is used in the function call then it should always be followed by keyword arguments. Positional arguments can be written in the beginning before any keyword argument is passed.

def test_args_2(x, y, z):
    print(x, y, z)
test_args_2(4, 5, 4) #allow
tst_args_2(2,3,z=4) # allow
test_args_2(4,y=5,z=3) #allow
test_args_2(x=2,y=3,z=5) #allow
tst_args_2(x=2,y=3,4) # not allow
tst_args_2(x=2,3,4) # not allow
tst_args_2(2,y=3,4) # not allow

Upvotes: 0

Atalajaka
Atalajaka

Reputation: 125

z will always be considered positional as long as you don't assign it a default value, for example:

def test_args_2(x, y, z=42):
    print(x, y, z)

You can read a more in-depth explanation here.

Upvotes: 0

Related Questions