[Python-3000] PEP 3102

Nick Coghlan ncoghlan at gmail.com
Tue Feb 19 11:49:28 CET 2008


Adam Olsen wrote:
> Whereas keyword-only arguments force explicitness (at the cost of
> brevity), positional-only arguments do the opposite.  The default
> already allows us to choose brevity when appropriate, and the only
> reason I see to force it is when there's a conflict with **kwargs.

Which for me happens when I have a method which I want to accept 
arbitrary keyword arguments (I'll grant that isn't very often, but it 
has happened). I have to choose between disallowing 'self' or '_self' as 
one of the no-longer-quite-so-arbitrary keyword arguments, or else I 
have to do the song and dance to implement manual unpacking.

> Such obscure features warrant an obscure yet well-named decorator, not
> an obscure syntax that's difficult to get help on.

It's difficult to handle this in a decorator, as the problem that occurs 
is the underlying function reporting duplicate definitions for a parameter.

 >>> def f(self, **kwds):
...     print self, kwds
...
 >>> f(1, self=2)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'self'

There really isn't a lot a decorator can do to prevent this, unless we 
modify function calls to permit direct assignment of the keywords 
dictionary without unpacking it. Then it would become possible to 
provide a decorator in functools along the lines of:

def positional_only(required=1):
     def wrap(f):
         @wraps(f)
         def wrapper(*args, **kwds):
             if len(args) < required:
                 raise TypeError("Need %d positional arguments "
                                 "(%d given)" % (required, len(args)))
             f(*args, **=kwds)

The idea of the **= syntax would be that the supplied dictionary is used 
directly as the arbitrary keywords parameter for the underlying 
function. Other named arguments would *not* be extracted from that 
dictionary (obviously, the above decorator would need further work in 
order to correctly handle parameters which can passed as either 
positional or keywords parameters).

Personally, I don't think the problem comes up often enough to be overly 
worried about it, as much as my sense of aesthetics would like to see an 
elegant solution (as judged by own personal definition of elegance of 
course ;)

We've also veered fairly far off topic for the Py3k list - further ideas 
for positional-only argument syntax or decorators should probably be 
kicked around on python-ideas rather than here or python-dev.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list