Positional argument follows keyword argument python ошибка

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

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.

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don’t have to provide it. If you don’t provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don’t need to use them, simply don’t specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

Update: This post was originally published on my blog decodingweb.dev as part of the Python Syntax Errors series. You can read the latest version on my blog for a 💯 user experience.

Python raises the “SyntaxError: positional argument follows keyword argument” error if you place one or more keyword arguments (e.g., age=35, name=John) before your positional arguments (e.g., 35, John) in a function call.

Based on Python syntax, keyword arguments must follow positional arguments and not the other way around:

def greet(name, message):
  return f'Hi {name}, {message}!'

# 🚫 SyntaxError
print(greet(name='John', 'Welcome'))

Enter fullscreen mode

Exit fullscreen mode

Here’s what the error looks like:

File /dwd/sandbox/test.py, line 5
  print(greet(name='John', 'Welcome!'))
                                      ^
SyntaxError: positional argument follows keyword argument

Enter fullscreen mode

Exit fullscreen mode

In the above example, the keyword argument name='John' shouldn’t appear before the positional argument 'Welcome' when calling the greet() function.

How to fix SyntaxError: positional argument follows keyword argument

To fix this syntax error, you have three options:

1. Pass keyword arguments after positional arguments
2. Pass all the arguments as positional arguments
3. Pass all the arguments as keyword arguments

Let’s explore each approach with some examples.

1. Pass keyword arguments after positional arguments: Based on Python syntax, keyword arguments must follow positional arguments:

def greet(name, message):
  return f'Hi {name}, {message}!'

# ✅ Correrct
print(greet('John', message='Welcome'))

# 🚫 Wrong
print(greet(name='John', 'Welcome'))

Enter fullscreen mode

Exit fullscreen mode

Even if only one keyword argument appears before a positional argument, you’ll get the «SyntaxError: positional argument follows keyword argument» error.

2. Pass all the arguments as positional arguments: In this approach, we need to make sure we pass the values in the order they appear in the function’s definition:

def greet(name, message):
  return f'Hi {name}, {message}!'

# ✅ Correct
print(greet('John', 'Welcome'))
# expected output: Hi John, Welcome!

# 🚫 Wrong
print(greet('Welcome', 'John'))
# unexpected output: Hi Welcome!, John

Enter fullscreen mode

Exit fullscreen mode

3. Pass all the arguments as keyword arguments: Unlike positional arguments, the order doesn’t matter when passing keyword arguments. However, names must be correct:

def greet(name, message):
  return f'Hi {name}, {message}!'

# ✅ Correct
print(greet(message='Welcome!', name='John'))

Enter fullscreen mode

Exit fullscreen mode

A quick refresher on positional and keyword arguments
When calling a function, we can either pass the arguments as positional or keyword arguments — or a combination of both.

Here are a few examples:

# 2 positional arguments
greet('John', 'Welcome!')

# 2 keyword arguments
greet(message='Welcome!', name='John')

# 1 positional argument, 1 keyword argument
greet('John', message='Welcome!')

Enter fullscreen mode

Exit fullscreen mode

If we pass arguments as positional arguments, we need to be aware of their order because Python will map the values to variables in the order they appear in the function’s definition.

def greet(name, message):
   return f'Hi {name}, {message}!'

# ✅ Correct
print(greet('John', 'welcome!'))

Enter fullscreen mode

Exit fullscreen mode

The order doesn’t matter with keyword arguments, though.

However, you need to provide the parameter name as it appears in the function’s definition.

If you want to use keyword arguments, remember to place them after the positional ones. Otherwise, Python’s interpreter raises the «SyntaxError: positional argument follows keyword argument» error.

You can also have your function accept positional-only arguments. You can do that by placing a / after your parameters:

# ✅ Correct
def greet(name, message, /):
   return f'Hi {name}, {message}!'

Enter fullscreen mode

Exit fullscreen mode

As a result, if you invoke the function with a keyword argument, Python raises a TypeError.

This is good practice when making APIs; Using positional-only arguments in APIs helps you avoid breaking changes if a parameter name is modified in the future.

Alternatively, you can make your arguments keyword-only by placing a * before them.

# ✅ Correct
def greet(name, *, message):
   return f'Hi {name}, {message}!'

Enter fullscreen mode

Exit fullscreen mode

You can also combine the two to make some arguments positional-only, some keyword-only, and some both of them (the standard form):

# ✅ Correct
def greet(name, /, age *, message):
   return f'Hi {name}, {message}!'

Enter fullscreen mode

Exit fullscreen mode

In the above example, the name parameter must be passed as a positional argument (must be the first argument passed), and age is a standard parameter, meaning it can be a positional or keyword argument. And message must be a keyword argument since it’s preceded by a *.

Here’s the blueprint from Python.org

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
      -----------    ----------     ----------
        |             |                  |
        |        Positional or keyword   |
        |                                - Keyword only
         -- Positional only

Enter fullscreen mode

Exit fullscreen mode

How do I know when to use positional arguments, and when to use keyword arguments? You may ask.

Here’s the rule of thumb:

You can use positional arguments when the order of the parameters matters when calling the function.

Keyword-only arguments are helpful when the argument names are meaningful, and the function’s behavior is easier to understand with explicit names, or when you want to avoid people depending on the order of the arguments.

And that’s how you’d handle the «SyntaxError: positional argument follows keyword argument» error in Python.

Alright, I think it does it. I hope this quick guide helped you solve your problem.

Thanks for reading.

Понравилась статья? Поделить с друзьями:
  • Porte avg ouverte ошибка citroen c4
  • Portal knights сетевая ошибка
  • Portal knights ошибка при запуске
  • Portal knights ошибка на непонятном языке
  • Portal knights ошибка steamworks