[Python-3000] Cleaning up argument list parsing (was Re: More wishful thinking)

Andrew McCollum mccollum at fas.harvard.edu
Wed Apr 19 20:42:21 CEST 2006


On 4/17/06, Guido van Rossum <guido at python.org> wrote:

> Here's a related but more complicated wish: define a function in such
> a way that certain parameters *must* be passed as keywords, *without*
> using *args or **kwds. This may require a new syntactic crutch.

I don't know if this counts as "not using *args or **kwds", but why can't
this simply be done with a decorator?  Here's a (tested) example:

"""
class KeywordError(TypeError):
    pass
    
def require_keywords(*keywords):
    def check_keywords(f):
        def new_f(*args, **kwds):
            
            for k in keywords:
                if k not in kwds:
                    raise KeywordError("%s() requires the keyword "
                                       "argument '%s'" % (f.func_name, k))
            
            return f(*args, **kwds)
        
        new_f.func_name = f.func_name
        new_f.func_doc = f.func_doc
        new_f.func_defaults = f.func_defaults
        return new_f
    
    return check_keywords

@require_keywords('font', 'size', 'color')
def write_text(s, font=None, size=None, color=None):
    pass
    
@require_keywords('paramA')
def example(paramA, paramB=10):
    print paramA, paramB

"""

Here's what happens when you call these functions:

"""
>>> example(paramA=5)
5 10

>>> example(paramB=5)
KeywordError: example() requires the keyword argument 'paramA'

>>> example(5, 10)
KeywordError: example() requires the keyword argument 'paramA'

>>> example(5, paramA=5)
TypeError: example() got multiple values for keyword argument 'paramA'
"""

As you can see, this method still prevents double-passing the arguments.
The major disadvantage that I can see is that the function signature of the
decorated function becomes (*args, **kwds).  By the way, this is my first
post to this list, so hello everybody.

	-Andrew McCollum




More information about the Python-3000 mailing list