[Python-ideas] Positional only arguments

Arnaud Delobelle arno at marooned.org.uk
Fri May 18 08:35:06 CEST 2007


On Wed, May 16, 2007 5:45 pm, Guido van Rossum wrote:
[...]
> But I'd love to see better syntax for positional-only arguments. What
> I would like to be able to do is somehow write a signature like this:
>
>   def foo(abc, xyz=42): ...
>
> where both arguments (if present) *must* be given using positional
> notation, so that foo(42) and foo(42, 24) are legal, but foo(abc=42)
> and foo(42, xyz=24) are illegal. (Alas, I don't have any clever
> suggestions.)

One could decorate foo with:

def posonly(f):
    def posf(*args, **kwargs): return f(*args, *kwargs)
    posf.__name__ = f.__name__
    return f

So:

@posonly
def foo(abc, xyz=42):...

would behave as you want.  Of course it doesn't have an interesting
signature.

By extension one could have the arglist element *(a, b, c) for
positional-only arguments and **(x, y, z) for keyword-only arguments:

def foo(*(abc, xyz=42)):...

def bar(a, b, **(x, y=2)):...
    # a and b are positional/keyword arguments
    # x is keyword-only and mandatory
    # y is keyword-only with a default value of 2

It sort of fits with the current use of * as when calling foo:

foo(my_abc, my_xyz)

is equivalent to

foo(*(my_abc, my_xyz))

-- 
Arnaud





More information about the Python-ideas mailing list