首页 > 解决方案 > Unnamed Arguments in Functions: Equivalent of R's Triple Dot

问题描述

Coming from R, I was wondering if there is an equivalent in Python of R's ...?

In R, the triple dot can be quite useful in functions as it allows to pass any kind of arguments (named, unnamed, any type, any class, etc.). For example

fun <- function (...) return(list(...))
fun(a=1, b=2, weather=c("sunny", "warm"))
# returns
# $a
# [1] 1

# $b
# [1] 2

# $weather
# [1] "sunny" "warm"

Is there an analogous in Python?

I would like to have a similar function

def fun(...): return (...)
# such that
fun(a=1, b=2)
# returns
# {'a':1, 'b':2} 
# or something similar

标签: python

解决方案


This is the way to receive any number of arguments:

def function(*arguments):
    print("received {} arguments".format(len(arguments)))

Then you can call it e.g. this way:

>>> function(5,5,6)
received 3 arguments

The arguments variable is a tuple containing all of the arguments.

On the other hand, if you want named arguments, you can do this:

def function(**keyword_arguments):
    print("received {} arguments".format(len(keyword_arguments)))

Then you can call it e.g. this way:

>>> function(a=4, b=7)
received 2 arguments

The keyword_arguments variable contains a dictionary of passed arguments.

See also the Python Documentation on Keyword Arguments.


推荐阅读