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?
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?
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.
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:
You're calling it with the
ckeyword argument by: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:Everywhere you call
their_function(myA, myB, myC), nowmyCis passed totheir_functionasd, 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 thatmyCwould have still been passed totheir_functionasc.Of course, this is probably overkill for obvious functions, such as
printoropenwhose, positional argument is natural. But I find it really reassuring to callopen(path, 'r', encoding='utf8'), rather thanopen(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:
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 aTypeErrorwhen passing a fourth argument as a positional one, ie without naming it.This helps you make your code a little more fool-proof, especially when defining functions with many positional or keyword arguments.