- What are keyword arguments in Python?
- Types of Arguments
- Positional arguments
- Keyword arguments
- Fixed arguments vs. arbitrary arguments
- Что такое *args и **kwargs в Python?
- Позиционные и именованные аргументы
- Оператор «звёздочка»
- Как пользоваться *args и **kwargs
- Итоги
- Python Keyword Arguments
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
What are keyword arguments in Python?
Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.
In Python, the terms parameter and argument are used interchangeably. However, there is a slight distinction between these two terms. Parameters are the input variables bounded by parentheses when defining a function, whereas arguments are the values assigned to these parameters when passed into a function (or method) during a function call.
def team(name, project):print(name, "is working on an", project)team("FemCode", "Edpresso")
In the example above, the function arguments are FemCode and Edpresso , whereas name and project are the function parameters.
Types of Arguments
There are two types of arguments: positional arguments and keyword arguments.
Positional arguments
Positional arguments are values that are passed into a function based on the order in which the parameters were listed during the function definition. Here, the order is especially important as values passed into these functions are assigned to corresponding parameters based on their position.
def team(name, project):print(name, "is working on an", project)team("FemCode", "Edpresso")
In these examples, we see that when the positions of the arguments are changed, the output produces different results. Though the code in example B isn’t wrong, the values that have been passed into the function are in the wrong order; thus, producing a result that does not match our desired output. Edpresso is the name of the project that is being worked on by the team, FemCode, not the other way around.
Now that the understanding is clear, let’s move on to keyword arguments.
Keyword arguments
Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = .
Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
def team(name, project):print(name, "is working on an", project)team(project = "Edpresso", name = 'FemCode')
As you can see, we had the same output from both codes although, when calling the function, the arguments in each code had different positions.
With keyword arguments, as long as you assign a value to the parameter, the positions of the arguments do not matter.
However, they do have to come after positional arguments and before default/optional arguments in a function call.
Default arguments are keyword arguments whose values are assigned at the time of function definition. Optional arguments are default arguments that, based on the values assigned to them (e.g., None or 0), can be disregarded.
def team(name, project, members=None):team.name= nameteam.project= projectteam.members= membersprint(name, "is working on an", project)team(name = "FemCode", "Edpresso")
The ‘Wrong’ code above generated a syntax error. In Python, a syntax error is basically an error that goes against a rule in Python. In terms of the above error, Python did not approve of the order in which the arguments were passed.
def team(name, project):print(number, name,"are working on an", project)team("The two members of", "FemCode", "Edpresso")
The above code throws a TypeError that draws your attention to the number of allowed input arguments.
Is there a way around this such that we can pass in more arguments than is allowed? Let’s find out!
Fixed arguments vs. arbitrary arguments
Up until this point, we have been dealing with fixed function arguments. This simply means that the number of arguments we previously passed into functions were always limited to a specific quantity since we knew the number of arguments needed in advance. Sometimes, we do not know the number of arguments needed in advance; thus, we need to input more arguments than previously mentioned in the function definition. How do we go about this?
Python allows us to do this through certain special syntaxes that are collectively known as arbitrary arguments (or variable-length arguments). Here, unlike with fixed arguments, parameters are not specified by distinct individual names, but rather a general term to better encapsulate the shared attribute of the type of arguments being passed into the function. These syntaxes are of the forms:
Что такое *args и **kwargs в Python?
Функции — это жизнь. Правда? Если вы только начали осваивать Python, неважно — первый ли это ваш язык программирования, или вы пришли в Python из другого языка, то вы уже знаете о том, что количество параметров в объявлении функции соответствует количеству аргументов, которые передают функции при вызове.
Это — основы. Это то, что помогает людям понимать окружающий мир. Но утверждение «количество параметров равно количеству аргументов» закладывает в голову новичка бомбу замедленного действия, которая срабатывает после того, как он увидит в объявлении функции таинственные конструкции *args или **kwargs .
Не позволяйте всяким значкам загонять себя в ступор. Тут нет ничего архисложного. В общем-то, если эти конструкции вам незнакомы — предлагаю с ними разобраться.
Позиционные и именованные аргументы
Для того чтобы разобраться с *args и **kwargs , нам нужно освоить концепции позиционных (positional) и именованных (keyword) аргументов.
Сначала поговорим о том, чем они отличаются. В простейшей функции мы просто сопоставляем позиции аргументов и параметров. Аргумент №1 соответствует параметру №1, аргумент №2 — параметру №2 и так далее.
def printThese(a,b,c): print(a, "is stored in a") print(b, "is stored in b") print(c, "is stored in c") printThese(1,2,3) """ 1 is stored in a 2 is stored in b 3 is stored in c """
Для вызова функции необходимы все три аргумента. Если пропустить хотя бы один из них — будет выдано сообщение об ошибке.
def printThese(a,b,c): print(a, "is stored in a") print(b, "is stored in b") print(c, "is stored in c") printThese(1,2) """ TypeError: printThese() missing 1 required positional argument: 'c' """
Если при объявлении функции назначить параметру значение по умолчанию — указывать соответствующий аргумент при вызове функции уже необязательно. Параметр становится опциональным.
def printThese(a,b,c=None): print(a, "is stored in a") print(b, "is stored in b") print(c, "is stored in c") printThese(1,2) """ 1 is stored in a 2 is stored in b None is stored in c """
Опциональные параметры, кроме того, можно задавать при вызове функции, используя их имена.
В следующем примере установим три параметра в значение по умолчанию None и взглянем на то, как их можно назначать, используя их имена и не обращая внимания на порядок следования аргументов, применяемых при вызове функции.
def printThese(a=None,b=None,c=None): print(a, "is stored in a") print(b, "is stored in b") print(c, "is stored in c") printThese(c=3, a=1) """ 1 is stored in a None is stored in b 3 is stored in c """
Оператор «звёздочка»
Оператор * чаще всего ассоциируется у людей с операцией умножения, но в Python он имеет и другой смысл.
Этот оператор позволяет «распаковывать» объекты, внутри которых хранятся некие элементы. Вот пример:
a = [1,2,3] b = [*a,4,5,6] print(b) # [1,2,3,4,5,6]
Тут берётся содержимое списка a , распаковывается, и помещается в список b .
Как пользоваться *args и **kwargs
Итак, мы знаем о том, что оператор «звёздочка» в Python способен «вытаскивать» из объектов составляющие их элементы. Знаем мы и о том, что существует два вида параметров функций. Вполне возможно, что вы уже додумались до этого сами, но я, на всякий случай, скажу об этом. А именно, *args — это сокращение от «arguments» (аргументы), а **kwargs — сокращение от «keyword arguments» (именованные аргументы).
Каждая из этих конструкций используется для распаковки аргументов соответствующего типа, позволяя вызывать функции со списком аргументов переменной длины. Например — создадим функцию, которая умеет выводить результаты, набранные учеником в тесте:
def printScores(student, *scores): print(f"Student Name: ") for score in scores: print(score) printScores("Jonathan",100, 95, 88, 92, 99) """ Student Name: Jonathan 100 95 88 92 99 """
Я не использовал при объявлении функции конструкцию *args . Вместо неё у меня — *scores . Нет ли тут ошибки? Ошибки здесь нет. Дело в том, что «args» — это всего лишь набор символов, которым принято обозначать аргументы. Самое главное тут — это оператор * . А то, что именно идёт после него, особой роли не играет. Благодаря использованию * мы создали список позиционных аргументов на основе того, что было передано функции при вызове.
После того, как мы разобрались с *args , с пониманием **kwargs проблем быть уже не должно. Имя, опять же, значения не имеет. Главное — это два символа ** . Благодаря им создаётся словарь, в котором содержатся именованные аргументы, переданные функции при её вызове.
def printPetNames(owner, **pets): print(f"Owner Name: ") for pet,name in pets.items(): print(f": ") printPetNames("Jonathan", dog="Brock", fish=["Larry", "Curly", "Moe"], turtle="Shelldon") """ Owner Name: Jonathan dog: Brock fish: ['Larry', 'Curly', 'Moe'] turtle: Shelldon """
Итоги
Вот несколько советов, которые помогут вам избежать распространённых проблем, возникающих при работе с функциями, и расширить свои знания:
- Используйте общепринятые конструкции *args и **kwargs для захвата позиционных и именованных аргументов.
- Конструкцию **kwarg s нельзя располагать до *args . Если это сделать — будет выдано сообщение об ошибке.
- Остерегайтесь конфликтов между именованными параметрами и **kwargs , в случаях, когда значение планируется передать как **kwarg -аргумент, но имя ключа этого значения совпадает с именем именованного параметра.
- Оператор * можно использовать не только в объявлениях функций, но и при их вызове.
Python Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print(«The youngest child is » + child3)
my_function(child1 = «Emil», child2 = «Tobias», child3 = «Linus»)
The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.