Calling with keyword arguments (f(x=1))
A keyword argument lets you say which parameter each value goes to, by writing name=value inside the call.
Used in 129 lessons of the course, from 00.01.
When you call a function, you can pass values by position or by name. By position, the order decides: f(1, 2). By name, you write parameter=value: f(a=1, b=2). The order stops mattering and the call reads on its own.
You see it in the course from lesson 00.01:
difflib.get_close_matches(key, GLOSSARY.keys(), n=3, cutoff=0.6)
Here key and GLOSSARY.keys() go by position. n=3 and cutoff=0.6 go by name. Without the names, 3 and 0.6 would be bare numbers and you couldn't tell what they mean. With them, the line explains what each value controls.
One rule: positional arguments come first, then the named ones. And the name must exist as a parameter of the function.
Reach for it when: a function takes several values and you want the call to be clear, or when you want to change just one option and leave the others at their defaults.
Examples
Common mistake
def area(width, height):
return width * height
print(area(width=3, high=4))Why: The name `high` is not a parameter of the function; it is called `height`. Python doesn't guess.
How to write it: Use the parameter's exact name: area(width=3, height=4).
Common mistake
def area(width, height):
return width * height
print(area(width=3, 4))Why: A positional argument can't come after a keyword argument.
How to write it: Put the positional ones first: area(3, height=4).
