[Tutor] Python question 4.8.2. Keyword Argument

dn PythonList at DancesWithMice.info
Wed Mar 6 20:31:56 EST 2024


On 7/03/24 05:11, ThreeBlindQuarks via Tutor wrote:
> 
> Desiree,
> 
> Others have responded to your question about the way python handles mixtures of arguments to a function so what I am adding is a bit different.
> 
> As you note, when you write your function that may be used by others, they may not know or care about subtle rules that positional arguments come first and are mandatory.
> 
> So, in some cases, I find a style useful that makes more or even all arguments to be keyword arguments with a default.
> 
> Your first argument of voltage could be written as voltage=NULL or anything else that is meaningful to you as a way of recognizing the user did not specify a value.
> 
> This means no error messages are supplied if the argument is not used so it is up to you, the programmer, to start your function body with appropriate code that detects what is missing and acts appropriately. Sometimes it means supplying an error message and/or returning with some error status. Other times, you can do anything from asking them to interactively supply a value (often not doable) to making up one with some calculation perhaps based on other arguments supplied.

+1

The case where it is acceptable to have Python splatting:

TypeError: function_name() missing .. required positional argument: ...

across the terminal is very rare. It might be OK if only you and I will 
ever call the function. Everyone else deserves better!

Let's say the wider system will give us a name or an id, and the 
function's task is to advise whether or not the name/id appears in some 
data-store, it seems reasonable to say that no-one would expect to 
utilise our (magnificent) function without providing the subject-matter. 
However, the operative word is "reasonable"!

Traditionally, pythonista have followed a free-wheeling EAFP* 
life-style. This has been changing, possibly with frequency of 
application to Data Science projects, to LBYL* (which is also how us 
old-timers were originally trained) - see also Type Hints.

* if don't know these acronyms/terms, please invest a little bit of 
valuable reading - and reflection...


Adding to the above, advice that as soon as the parameter-list reaches 
three elements, switch to named-parameters; simply because the process 
of checking relative-positioning is a recipe for eye-strain and 
cross-eyes (both meanings)!

-- 
Regards,
=dn


More information about the Tutor mailing list