[Python-ideas] Positional only arguments
Steven Bethard
steven.bethard at gmail.com
Sun May 20 22:32:52 CEST 2007
On 5/20/07, Arnaud Delobelle <arno at marooned.org.uk> wrote:
> On Sun, May 20, 2007 4:24 pm, Steven Bethard wrote:
> > I've also noticed that the current @posonly decorator won't solve the
> > dict() and dict.update() problem::
[snip]
> Yes. I don't see how this can be avoided in pure Python. But I came up
> with the solution below (I'm not saying it's good :)
[snip]
> >>> class MyDict(object):
> >>> @posonly(2, safe_kwargs=True)
> >>> def update(safe_kwargs, self, container=None, **kwargs):
> >>> return self, container, safe_kwargs, kwargs
Since currently the only use case for positional-only arguments is the
dict() and dict.update() signature, I would simplify the decorator to
look like::
def positional_kwargs(func):
def func_with_positional_kwargs(*args, **kwargs):
n_missing = func.func_code.co_argcount - len(args) - 1
args += func.func_defaults[-n_missing - 1:-1]
args += (kwargs,)
return func(*args)
functools.update_wrapper(func_with_positional_kwargs, func)
return func_with_positional_kwargs
You could use it like::
>>> class D(object):
... @positional_kwargs
... def __init__(self, container=None, kwargs={}):
... print self, container, kwargs
...
>>> d = D(self=1, container=2)
<__main__.D object at 0x00F05E30> None {'self': 1, 'container': 2}
That's not too bad because you're just replacing **kwargs with
kwargs={}. And it's relatively easy to explain. I guess that would
cover all the use cases I care about.
I still lean slightly towards the lone '*' and '**' proposal,
particularly since one of them is already introduced by `PEP 3102`_,
but putting this decorator in functools is a good backup plan.
.. _PEP 3102: http://www.python.org/dev/peps/pep-3102/
STeVe
--
I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
--- Bucky Katt, Get Fuzzy
More information about the Python-ideas
mailing list