[Python-ideas] Improving fn(arg=arg, name=name, wibble=wibble) code
Anders Hovmöller
boxed at killingar.net
Sat Sep 8 08:21:56 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
> On 8 Sep 2018, at 13:17, Jonathan Fine <jfine2358 at gmail.com> wrote:
>
> I thank Steve D'Aprano for pointing me to this real-life (although
> perhaps extreme) code example
>
> https://github.com/Tinche/aiofiles/blob/master/aiofiles/threadpool/__init__.py#L17-L37
> <code>
> def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None,
> closefd=True, opener=None, *, loop=None, executor=None):
> return AiofilesContextManager(_open(file, mode=mode, buffering=buffering,
> encoding=encoding, errors=errors,
> newline=newline, closefd=closefd,
> opener=opener, loop=loop,
> executor=executor))
>
>
> @asyncio.coroutine
> def _open(file, mode='r', buffering=-1, encoding=None, errors=None,
> newline=None,
> closefd=True, opener=None, *, loop=None, executor=None):
> """Open an asyncio file."""
> if loop is None:
> loop = asyncio.get_event_loop()
> cb = partial(sync_open, file, mode=mode, buffering=buffering,
> encoding=encoding, errors=errors, newline=newline,
> closefd=closefd, opener=opener)
> f = yield from loop.run_in_executor(executor, cb)
>
> return wrap(f, loop=loop, executor=executor)
> </code>
>
>
> Anders Hovmöller has proposed a Python syntax extension to improve
> this code. It provides, for example
> return wrap(f, *, loop, executor)
> as a shorthand for
> return wrap(f, loop=loop, executor=executor)
>
> See: https://mail.python.org/pipermail/python-ideas/2018-September/053207.html
>
> I'd like us, in this thread, to discuss OTHER possible ways of
> improving this code. This could include refactoring, and the
> introduction of tools. I'm particularly interested in gathering
> alternatives, and at this time not much interesting in "knowing which
> one is best".
>
> --
> Jonathan
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
More information about the Python-ideas
mailing list