简体   繁体   中英

How can I write a python function to accept *arguments and a keyword argument?

I feel like there must be something simple I'm missing here. Here's what I want to do:

>>> def x(*args, a=False):
...   print args, a

>>> x(1,2)
(1,2) False

>>> x(1,2,3, a=True)
(1,2,3) True

But you can't define a function like that.

I know this would work, but it doesn't seem as nice:

>>> def x(*args, **kwargs):
...   if 'a' in kwargs:
...       a = kwargs['a']
...   else
...       a = False
...   print args, a

What's the best way to do this?
I'm using python 2.6

I think what you have is the only way. But you can write it nicer:

def x(*args, **kwargs):
    a = kwargs.get('a', False)
    print args, a

x(1,2,3,a=42)

Just found this http://www.python.org/dev/peps/pep-3102/

The first change is to allow regular arguments to appear after a varargs argument:

 def sortwords(*wordlist, case_sensitive=False): ... 

This function accepts any number of positional arguments, and it also accepts a keyword option called 'case_sensitive'.

So it's coming in Python 3

Well all *args really is a variable list of arguments and all **kwargs really is a dictionary keyword-only arguments.

Unless I am misunderstanding, why not just do this?

def x(args, a=False):
    print args, a

x((1,2),True) #<- just passes in a list instead of special list and dict

output
(1,2) True

x((1,2))

output
(1,2) False

It is not as pythonic without the variable *argument list and detection of the **kwargs keyword-only arguments dict but probably works for your needs.

您必须采取第二个选择,或者您必须重新排序参数,以便首先使用默认参数:

def x(a=False, *args):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM