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?
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With