Positional argument follows keyword argument как исправить

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться в Python:

SyntaxError : positional argument follows keyword argument

Эта ошибка возникает, когда вы используете позиционный аргумент в функции после использования аргумента ключевого слова .

Вот разница между ними:

Позиционные аргументы — это аргументы, перед которыми нет «ключевого слова».

  • Пример: my_function (2, 2)

Аргументы ключевых слов — это аргументы , перед которыми стоит «ключевое слово».

  • Пример: my_function(a=2, b=2)

Если вы используете позиционный аргумент после аргумента ключевого слова, Python выдаст ошибку.

  • Пример: my_function(a=2, 2)

В следующем примере показано, как эта ошибка может возникнуть на практике.

Пример: Аргумент позиции следует за аргументом ключевого слова

Предположим, у нас есть следующая функция в Python, которая умножает два значения, а затем делит на третье:

def do_stuff (a, b):
 return a * b / c

В следующих примерах показаны допустимые и недопустимые способы использования этой функции:

Правильный способ №1: все позиционные аргументы

Следующий код показывает, как использовать нашу функцию со всеми позиционными аргументами:

do_stuff( 4 , 10 , 5 )

8.0

Никакой ошибки не возникает, потому что Python точно знает, какие значения использовать для каждого аргумента в функции.

Верный способ № 2: все аргументы ключевых слов

Следующий код показывает, как использовать нашу функцию со всеми аргументами ключевого слова:

do_stuff(a= 4 , b= 10 , c= 5 )

8.0

И снова ошибка не возникает, потому что Python точно знает, какие значения использовать для каждого аргумента в функции.

Действенный способ № 3: позиционные аргументы перед ключевыми аргументами

Следующий код показывает, как использовать нашу функцию с позиционными аргументами, используемыми перед аргументами ключевого слова:

do_stuff(4, b=10, c=5)

8.0

Никакой ошибки не возникает, потому что Python знает, что аргументу a должно быть присвоено значение 4 .

Неверный способ: позиционные аргументы после аргументов ключевого слова

Следующий код показывает, как мы можем попытаться использовать функцию с позиционными аргументами, используемыми после аргументов ключевого слова:

do_stuff(a= 4, 10, 5)

SyntaxError : positional argument follows keyword argument

Возникает ошибка, потому что мы использовали позиционные аргументы после аргументов ключевого слова.

В частности, Python не знает, следует ли присваивать значения 10 и 5 аргументам b или c , поэтому он не может выполнить функцию.

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами

In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python

An argument is a value provided to a function when you call that function. For example, look at the below program –

Python

def calculate_square(num):

    return num * num

result = calculate_square(10)

print(result)

The calculate_square() function takes in an argument num which is an integer or decimal input, calculates the square of the number and returns the value.

Keyword and Positional Arguments in Python

There are two kind of arguments, namely, keyword and positional. As the name suggests, the keyword argument is identified by a function based on some key whereas the positional argument is identified based on its position in the function definition. Let us have a look at this with an example.

Python

def foo(a, b, c=10):

    print('a =', a)

    print('b =', b)

    print('c =', c)

print("Function Call 1")

foo(2, 3, 8)

print("Function Call 2")

foo(2, 3)

print("Function Call 3")

foo(a=2, c=3, b=10)

Output:

Function Call 1
a = 2
b = 3
c = 8
Function Call 2
a = 2
b = 3
c = 10
Function Call 3
a = 2
b = 10
c = 3

Explanation:

  1. During the first function call, we provided 3 arguments with any keyword. Python interpreted in order of how they have been defined in the function that is considering position of these keywords.
  2. In the second function call, we provided 2 arguments, but still the output is shown because of we provided 2 positional argument and the function has a default value for the final argument c. So, it takes the default value into account for the final argument.
  3. In the third function call, three keyword arguments are provided. The benefit of providing this keyword argument is that you need not remember the positions but just the keywords that are required for the function call. These keywords can be provided in any order but function will take these as key-value pairs and not in the order which they are being passed.

SyntaxError: positional argument follows keyword argument

In the above 3 cases, we have seen how python can interpret the argument values that are being passed during a function call. Now, let us consider the below example which leads to a SyntaxError.

Python

def foo(a, b, c=10):

    print('a =', a)

    print('b =', b)

    print('c =', c)

print("Function Call 4")

foo(a=2, c=3, 9)

Output:

File "<ipython-input-40-982df054f26b>", line 7
    foo(a=2, c=3, 9)
                 ^
SyntaxError: positional argument follows keyword argument

Explanation:

In this example, the error occurred because of the way we have passed the arguments during the function call. 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. Here, a=2 and c=3 are keyword argument. The 3rd argument 9 is a positional argument. This can not be interpreted by the python as to which key holds what value. The way python works in this regards is that, it will first map the positional argument and then any keyword argument if present.

How to avoid the error – Conclusion

Last Updated :
28 Nov, 2021

Like Article

Save Article

Table of Contents
Hide
  1. What is SyntaxError: positional argument follows keyword argument?
  2. How to fix SyntaxError: positional argument follows keyword argument?
    1. Scenario 1 – Use only Positional Arguments.
    2. Scenario 2 – Use only Keyword Arguments.
    3. Scenario 3 – Use Positional arguments first, followed by Keyword Arguments.
  3. Conclusion

If you provide the keyword argument first followed by a positional argument, the Python interpreter will raise SyntaxError: positional argument follows keyword argument.

In this tutorial, we will learn what SyntaxError: positional argument follows keyword argument means and how to resolve this error with examples.

An argument is a variable, value, or object passed to a method or function as an input. We have two types of arguments in Python, and we can pass these arguments while calling the methods.

Positional Argument -The positional arguments are the one that does not have any keyword in front of them.

Example

result = add_numbers(10, 20, 30)

Keyword Argument -The Keyword arguments are the one that has a keyword in front of them.

Example

result = add_numbers(a=10, b=20, c=30)

Every programming language has its own set of rules. These rules are referred to as the syntax that needs to be followed while programming.

The positional and keyword arguments must appear in a specific order; otherwise, the Python interpreter will throw a Syntax error.

The Python rule says positional arguments must appear first, followed by the keyword arguments if we are using it together to call the method.

The SyntaxError: positional argument follows keyword argument means we have failed to follow the rules of Python while writing a code.

Let us take a simple example to demonstrate this error.

# Method that takes 3 arguments and returns sum of it
def add_numbers(a, b, c):
    return a+b+c

# call the method by passing the arguments
result = add_numbers(a=10, 20, 30)

# print the output
print("Addition of numbers is", result)

Output

  File "c:PersonalIJSCodemain.py", line 8
    result = add_numbers(a=10, 20, 30)
                                     ^
SyntaxError: positional argument follows keyword argument

We have passed the Keyword argument first in the above code and then followed by the Positional argument which breaks the rule and hence we get the SyntaxError.

How to fix SyntaxError: positional argument follows keyword argument?

There are several ways to fix the error. Let us look at all the correct ways to call the methods in Python.

Scenario 1 – Use only Positional Arguments.

The easier way to fix the issue is to use only Positional arguments while calling the method in Python.

Let us fix our example by passing only positional arguments and see what happens when we run the code.

# Method that takes 3 arguments and returns sum of it
def add_numbers(a, b, c):
    return a+b+c

# call the method by passing only positional arguments
result = add_numbers(10, 20, 30)

# print the output
print("Addition of numbers is", result)

Output

Addition of numbers is 60

The code runs without any error as Python knows which values to use for each argument in the function.

Scenario 2 – Use only Keyword Arguments.

Another way to resolve the error is to use only the Keyword arguments while calling the method in Python.

# Method that takes 3 arguments and returns sum of it
def add_numbers(a, b, c):
    return a+b+c


# call the method by passing only keyword arguments
result = add_numbers(a=10, b=20, c=30)

# print the output
print("Addition of numbers is", result)

Output

Addition of numbers is 60

The code runs without any error as Python knows which values to use for each argument in the function.

Scenario 3 – Use Positional arguments first, followed by Keyword Arguments.

If you need to use both positional and keyword arguments, you need to abide by the rules of Python.

The Positional arguments should always appear first, followed by the keyword arguments.

In the below example, we have fixed the issue by passing the two positional arguments first and then a keyword argument.

# Method that takes 3 arguments and returns sum of it
def add_numbers(a, b, c):
    return a+b+c


# pass all positional arguments first and then keyword arguments
result = add_numbers(10, 20, c=30)

# print the output
print("Addition of numbers is", result)

Output

Addition of numbers is 60

Conclusion

In Python, the SyntaxError: positional argument follows keyword argument occurs if you pass keyword arguments before the positional arguments. Since Python interprets positional arguments in the order in which they appear first and then followed by the keyword arguments as next.

We can resolve the SyntaxError by providing all the positional arguments first, followed by the keyword arguments at last.

Выдает ошибку:

await message.bot.message(chat_id=config.GROUP_ID, message.message_id)
                                                                         ^
SyntaxError: positional argument follows keyword argument

Как исправить?


  • Вопрос задан

    более года назад

  • 3835 просмотров

message.bot.message(message.message_id, chat_id=config.GROUP_ID)

Поменять местами аргументы, и хотя бы пользоваться переводчиком по минимуму

После именованных (chat_id= ) аргументов уже нельзя использовать позиционные (без указания имени аргумента). Т.е. или все передавать без имени, или явно указывать название второго аргумента.

Пригласить эксперта


  • Показать ещё
    Загружается…

23 мая 2023, в 11:54

12000 руб./за проект

23 мая 2023, в 11:12

15000 руб./за проект

23 мая 2023, в 11:05

5000 руб./за проект

Минуточку внимания

When working with Python functions, you might encounter an error as follows:

SyntaxError: positional argument follows keyword argument

This error usually occurs when you call a function that has both positional and named parameters.

In Python 2, the error message is slightly reworded as:

SyntaxError: non-keyword arg after keyword arg

Both error messages give us hints on how to fix this error. This article explains the error in more detail and shows you how to fix it.

How this error happens

This error happens when you call a function and place an unnamed argument next to a named argument.

Let’s see an example that causes this error. Write a function named greet() with the following parameters:

def greet(name, age, hobby):
    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"Hobby: {hobby}")

Next, call the function and pass the arguments as shown below:

greet("Nathan", age=28, "Coding")

Output:

Traceback (most recent call last):
  File "main.py", line 6
    greet("Nathan", age=28, "Coding")
                                    ^
SyntaxError: positional argument follows keyword argument

The error complains that we placed a positional argument next to the keyword argument.

A keyword argument (also known as named argument) is a value that you pass into a function with an identifying keyword or name.

By contrast, a positional argument is an unnamed argument, and is identified by its position in the function call.

By default, Python arguments are positional arguments, and they must not be specified after keyword arguments when you call a function.

How to fix this error

To resolve this error, you need to make sure that you don’t pass any positional arguments after keyword arguments.

You need to pass another keyword argument after the keyword argument age= as follows:

def greet(name, age, hobby):
    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"Hobby: {hobby}")

greet("Nathan", age=28, hobby="Coding")  # ✅

You can use keyword arguments to pass arguments in a different order than the defined parameters.

All following examples could work:

greet("Nathan", hobby="Coding", age=28)
greet(hobby="Coding", age=28, name="Nathan")
greet(age=28, name="Nathan", hobby="Coding")

Keyword arguments are optional, so you can also pass the same arguments without giving them names.

But you need to pass them in the same order as the parameters defined in the function:

greet("Nathan", 28, "Coding")

Another thing that can cause this error is when you mistyped the keyword argument using the comparison == operator.

Pay close attention to the hobby argument below:

greet(name="Nathan", age=28, hobby=="Coding")


# Traceback (most recent call last):
#   File "main.py", line 7
#     greet(name="Nathan", age=28, hobby=="Coding")
#                                        ^
# SyntaxError: positional argument follows keyword argument

In this example, we intend to pass a keyword argument named hobby, but the comparison operator turns the named argument into an expression that returns either True or False.

When passing keyword arguments, make sure that you use the assignment = operator to avoid this error.

I hope this tutorial is helpful. Happy coding! 👍

Добавить комментарий