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

Michael Selik mike at selik.org
Wed Sep 12 21:21:32 EDT 2018


On Sat, Sep 8, 2018 at 4:17 AM 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


It's hard to know from just a brief glance how the "private" _open function
will be used. Using GitHub's repo search, it looks like it's only called
once and only in this module. Since it has essentially the same signature
as the "public" open function, why not just use *args and **kwds for the
private _open?

Here's a quick refactor that emphasizes the pass-through relationship of
open and _open:

    def open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None,
             closefd=True, opener=None, *, loop=None, executor=None):
        return AiofilesContextManager(_open(**locals()))

    @asyncio.coroutine
    def _open(file, *args, **kwds):
        """Open an asyncio file."""
        executor = kwds.pop('executor')
        loop = kwds.pop('loop')
        if loop is None:
            loop = asyncio.get_event_loop()

        callback = partial(sync_open, file, *args, **kwds)
        f = yield from loop.run_in_executor(executor, callback)
        return wrap(f, loop=loop, executor=executor)


I normally dislike the use of **locals(), but here it helps make explicit
that the "public" open function passes all arguments through to its helper.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180912/27a96a90/attachment.html>


More information about the Python-ideas mailing list