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

I feel that there must be something simple, I am absent here. Here is 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 cannot define such a function.

I know this will work, but it doesn't look so nice:

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

What is the best way to do this?
I am using python 2.6

+3
source share
4 answers

I think you have the only way. But you can write this better:

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

x(1,2,3,a=42)
+5
source

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

The first change is to allow the regular arguments appearing after the varargs argument:

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

, , 'Case_sensitive'.

, Python 3

+3

Well, all * args really is a variable argument list, and all ** kwargs really are dictionary-only arguments.

If I do not understand, why not just do it?

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's not like pythonic without a list of * argument variables and argument detection ** kwargs is for keywords only, but probably works for your needs.

0
source

You must either make your second choice, or you must reorder the arguments, so there must first be an argument with a default value:

def x(a=False, *args):
0
source

Source: https://habr.com/ru/post/1783790/


All Articles