In ruby it is idiomatic to write a function that may be called like this:
open_database(:readonly) // or
open_database(:readonly, :remote, :force)
In these cases the :readonly are "symbols" and are used as "flags" to modify the behavior of the open_database call.
We would implement this as follows in ruby:
def func(*params)
if params.include? :readonly
puts "readonly"
end
end
What is the idiomatic way to do this in Python?
The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.
Pass by value is a way of passing the value to a function so as to use that value within that function. Because whatever changes you do to that value within that function will not be visible outside that function.
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
There is no such syntactic sugar on Python.
The correct way to do this would be to use default keyword arguments:
def open_database(readonly=False, remote=False, force=False):
# ...
You can then:
open_database(readonly=True, force=True) # remote=False (default)
If you want to get as close as possible to ruby, you can do argument unpacking:
def specify_flags(*args):
return {x: True for x in args}
open_database(**specify_flags('readonly', 'force')) # Same as readonly=True, force=True
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