Code style in using argument names

224 Views Asked by At

What's the recommended style for argument names?

open(file='myfile.txt')

or

open('myfile.txt')

PEP8 Style Guide For Python doesn't mention anything about this. When do I use one or the other?

2

There are 2 best solutions below

0
On

The main benefit I see in using explicit names is that the modification of a function's signature will have less impact on code relying on it.

For instance, say you're using a module's function, defined as:

their_function(a, b, c=1)

You're calling it with the c keyword argument by:

their_function(myA, myB, myC)

But now, the module's developers find it useful to have another keyword argument, and in their mind, it makes more sense that it comes before c. So now, the function is:

their_function(a, b, d=2, c=1)

Everywhere you call their_function(myA, myB, myC), now myC is passed to their_function as d, and everything is messed up.

On the other hand, had you called it by their_function(myA, myB, c=myC), the mapping of the keyword arguments would have been so that myC would have still been passed to their_function as c.

Of course, this is probably overkill for obvious functions, such as print or open whose, positional argument is natural. But I find it really reassuring to call open(path, 'r', encoding='utf8'), rather than open(path, 'r', 'utf8'), because even if I got the order wrong, the behaviour would still be as expected.


As for me, except in a few cases where it would be counter-intuitive, I tend to force the use of the names for the keyword arguments.

Python 3, from some version on, allows you to do the following:

def my_function(a, b, *, c=1):
    pass

Here, the use of the splat operator * alone tells Python that no positional argument can be found after the third one. This will result in a TypeError when passing a fourth argument as a positional one, ie without naming it.

>>> my_function(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: my_function() missing 1 required positional argument: 'b'

>>> my_function(1, 2)
# OK

>>> my_function(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: my_function() takes 2 positional arguments but 3 were given

>>> my_function(1, 2, c=3)
# OK

This helps you make your code a little more fool-proof, especially when defining functions with many positional or keyword arguments.

0
On

You'll get different opinions. Personally I would argue that using keyword arguments whenever possible is strictly better because it attaches human readable semantics to a function call. The reader has a decent shot at guessing what the arguments are supposed to be without inspecting the code/docs any further.

However, I do sometimes omit the keyword(s) when using well-known functions.