Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing options to a function

Tags:

python

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?

like image 350
pitosalas Avatar asked May 10 '18 12:05

pitosalas


People also ask

How do you pass multiple parameters to a function?

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.

Can we pass values to a 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.

How do you pass a parameter to a function in Python?

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.


1 Answers

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
like image 109
Matias Cicero Avatar answered Sep 20 '22 20:09

Matias Cicero