Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

variadic functions - Python, default keyword arguments after variable length positional arguments

I thought I could use named parameters after variable-length positional parameters in a function call in Python 2, but I get a SyntaxError when importing a python class. I'm writing with the following "get" method, for example:

class Foo(object):
    def __init__(self):
        print "You have created a Foo."

    def get(self, *args, raw=False, vars=None):
        print len(args)
        print raw
        print vars

The error looks like:

def get(self, *args, raw=False, vars=None):
                     ^
SyntaxError: invalid syntax

I'd like to be able to call the method several ways:

f = Foo()
f.get(arg1, arg2)
f.get(arg1, raw=True)
f.get(arg1, arg2, raw=True, vars=something)

etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It does work, but only in Python 3. See PEP 3102. From glancing over the "what's new" documents, it seems that there is no 2.x backport, so you're out of luck. You'll have to accept any keyword arguments (**kwargs) and manually parse it. You can use d.get(k, default) to either get d[k] or default if that's not there. To remove an argument from kwargs, e.g. before calling a super class' method, use d.pop.


Note that in def get(self, *args, raw=False, vars=None):, the raw=False and vars=None have nothing to do with keyword arguments. Those are default argument values. Arguments with a default value may be passed positionally, and arguments without a default value may be passed by keyword:

def f(a=1): pass
f(2)  # works, passing a positionally
def f(a): pass
f(a=2)  # works, passing a by keyword

Similarly, keyword-only arguments are not required to have a default value. Coming after the *args argument is what marks them as keyword-only, not the presence of a default value:

def f(*args, a): pass
# a is a mandatory, keyword-only argument

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...