Skip to content
Advertisement

format strings and named arguments in Python

Case 1:

JavaScript

It will give KeyError: 'arg1' because I didn’t pass the named arguments.

Case 2:

JavaScript

Now it will work properly because I passed the named arguments. And it prints '10 20'

Case 3:

And, If I pass wrong name it will show KeyError: 'arg1'

JavaScript

But,

Case 4:

If I pass the named arguments in wrong order

JavaScript

It works…

and it prints '20 10'

My question is why does it work and what’s the use of named arguments in this case.

Advertisement

Answer

Named replacement fields (the {...} parts in a format string) match against keyword arguments to the .format() method, and not positional arguments.

Keyword arguments are like keys in a dictionary; order doesn’t matter, as they are matched against a name.

If you wanted to match against positional arguments, use numbers:

JavaScript

In Python 2.7 and up, you can omit the numbers; the {} replacement fields are then auto-numbered in order of appearance in the formatting string:

JavaScript

The formatting string can match against both positional and keyword arguments, and can use arguments multiple times:

JavaScript

Quoting from the format string specification:

The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument.

Emphasis mine.

If you are creating a large formatting string, it is often much more readable and maintainable to use named replacement fields, so you don’t have to keep counting out the arguments and figure out what argument goes where into the resulting string.

You can also use the **keywords calling syntax to apply an existing dictionary to a format, making it easy to turn a CSV file into formatted output:

JavaScript

Here, picture, link, description and price are all keys in the row dictionary, and it is much easier to see what happens when I apply the row to the formatting string.

Advertisement