Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse arguments in an inner function?

Tags:

r

I have a function do_something that receives four arguments and calls an inner function get_options:

do_something <- function(name, amount, manufacturer="abc", width=4){ 
    opts <- get_options(amount, manufacturer = manufacturer, width = width)
}

get_options <- function(amount, manufacturer="abc", width = 4) { 
    opts <- validate_options(manufacturer, width)
}

Sometimes I do get_options(400), other times I want to override the arguments get_options(400, manufacturer = "def"), other times I call do_something("A", 400), or do_something("A", 400, width=10).

It seems like I'm being redundant by specifying the same default values for my arguments in both functions. Is there a better way to have them share these defaults?

like image 633
nachocab Avatar asked Apr 04 '13 10:04

nachocab


People also ask

What do you know about function arguments?

Let’s update what you know about functions now that you’ve spent some time exploring how function arguments work: As well as supporting code reuse, functions can hide complexity. If you have a complex line of code you intend to use a lot, abstract it behind a simple function call.

What happens when you change the value of a function argument?

If the variable in the function’s suite is changed, the value in the code that called the function changes, too. Think of the argument as an alias to the original variable. To work out what Tom and Sarah are arguing about, let’s put their functions into their very own module, which we’ll call mystery.py.

What is the use of inner functions?

A common use case of inner functions arises when you need to protect, or hide, a given function from everything happening outside of it so that the function is totally hidden from the global scope. This kind of behavior is commonly known as encapsulation.

How do you reuse a function in Python?

Reusing code is key to building a maintainable system. And when it comes to reusing code in Python, it all starts and ends with the humble function. Take some lines of code, give them a name, and you’ve got a function (which can be reused).


1 Answers

You can use the ellipsis (...) and only give defaults to the lowest level function:

do_something <- function(name, amount, ...){ 
    opts <- get_options(amount, ...)
}

get_options <- function(amount, manufacturer="abc", width = 4) { 
    opts <- validate_options(manufacturer, width)
}

You should still be able to run all of the below:

get_options(400)
get_options(400, manufacturer = "def")
do_something("A", 400)
do_something("A", 400, width=10)

and with the same results.

like image 56
flodel Avatar answered Oct 10 '22 13:10

flodel