[Python-ideas] Improving fn(arg=arg, name=name, wibble=wibble) code

Ben Lewis benlewisj at gmail.com
Sat Sep 8 19:40:23 EDT 2018

> It’s obvious but there is one easy way to shorten the code: using
> **kwargs. It’s way shorter but the down sides are:

- the “real” function signature gets hidden so IDEs for example won’t pick
> it up
> - the error when you make a mistake when calling is not in your code
> anymore but one level down.

This is confusing. One could imagine solving this specific case by having a
> type annotation of “this function has the types of that function”. Maybe:
> def _open(*args: args_of_(sync_open), **kwargs: kwargs_of(sync_open) ->
> return_of(sync_open): But of course this only solves the case where there
> is a 1:1 mapping. / Anders

These problems could be solved by a decorator that accepts string
representation of the signature. The decorator would then have to parse the
signature at importing time and set it to the __signature__ attribute on
the resultant function. This decorator would also need to bind the
arguments e.g. sig.bind(*args, **kwargs), to handle out of order positional
arguments. Therefore this would raise an error in the decorator,
essentially solving your second point.

This would make the example look like this, a lot clearer in my opionion:

@signature('''(file, mode='r', buffering=-1, encoding=None, errors=None,
                       closefd=True, opener=None, *, loop=None,
def open(*args, **kwargs):
      return AiofilesContextManager(_open(*args, **kwargs))

def _open(*args, loop=None, executor=None, **kwargs):
     """Open an asyncio file."""
     if loop is None:
         loop = asyncio.get_event_loop()
     cb = partial(sync_open, *args, **kwargs)
     f = yield from loop.run_in_executor(executor, cb)

     return wrap(f, loop=loop, executor=executor)

Ben Lewis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180909/9ad6fc86/attachment-0001.html>

More information about the Python-ideas mailing list