Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have required keyword arguments in Javascript or Python?

Can you have required keyword arguments in javascript or python? Is this a common feature of programming languages, or is it new and rare? They would be analogous to this implementation of keyword arguments in Ruby in Ruby 2.1+

def obvious_total(subtotal:, tax:, discount:)
  subtotal + tax - discount
end

obvious_total(subtotal: 100, tax: 10, discount: 5) # => 105

(The above example comes directly from https://robots.thoughtbot.com/ruby-2-keyword-arguments)

I'd like to know because I was really interested in the perspective of the author of the above page. He basically suggests that required keyword arguments would help coders understand each other's code later on down the line, while only sacrificing succintness. Personally, I think that that is a decent trade off, and I wonder if it is commonly practiced or not.

It is quite a common occurrence, I think, to find poorly documented code, and to wonder which argument does what. That's why I always try to put good and succinct instructions at my methods. I could be crazy and this is a completely unnecessary feature, after all, I'm just a newbie coder who scripts stuff when he gets lazy.

like image 408
Thonanth Siddef Avatar asked Jun 15 '16 07:06

Thonanth Siddef


1 Answers

PEP-3102 introduced "keyword-only arguments", so in Python 3.x you could do:

def obvious_total(*, subtotal, tax, discount):
    """Calculate the total and force keyword arguments."""
    return subtotal + tax - discount

In use:

>>> obvious_total(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: obvious_total() takes 0 positional arguments but 3 were given
>>> obvious_total(subtotal=1, tax=2, discount=3)
0

In JavaScript there is no way to have keyword arguments at all. The convention for this would be to define a single positional argument into which the user passes an object literal:

function obviousTotal(input) {
    return input.subtotal + input.tax - input.discount
}

and then pass an object literal as input. In use:

> obviousTotal({ subtotal: 1, tax: 2, discount: 3 })
0

ES6 lets you simplify this a bit with destructuring:

function obviousTotal({ discount, subtotal, tax }) {
    return subtotal + tax - discount;
}

but there is still no native support for required keyword arguments.

like image 61
jonrsharpe Avatar answered Sep 16 '22 15:09

jonrsharpe